1

I have been looking into this matter for some time now. I have the basic concept and now trying to implement the socket communication between ASP.NET and android. I am using the basic windows System.Net.Sockets to work this out. I am getting a connection as I try to debug my application line by line which tells that my server is working but the problem is that the C# line gets stuck at sender.Receive(bytes).

This is my android side server code for TCPServer

public class TCPServer extends Thread {
    public static final int SERVER_PORT = 11000;
    private boolean running = false;
    private PrintWriter mOut;
    private OnMessageReceived messageListener;


    public TCPServer(OnMessageReceived messageListener)
    {
        this.messageListener = messageListener;
    }

    public void sendMessage(String message)
    {
        if(mOut != null && !mOut.checkError())
        {
            mOut.println(message);
            mOut.flush();
        }
    }

    @Override
    public void run()
    {
        super.run();
        running=true;
        try {
            ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
            Socket client = serverSocket.accept();
            try {
                //sends the message to the client
                mOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);

                //read the message received from client
                BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));

                //in this while we wait to receive messages from client (it's an infinite loop)
                //this while it's like a listener for messages
                while (running) {
                    String message = in.readLine();

                    if (message != null && messageListener != null) {

                        messageListener.messageReceived(message);
                        sendMessage("OK Message is received here");
                        //the line above and below is also not helping me with my problem
                        mOut.println("OK: FROM ACOM");
                    }
                }
            }
            catch (Exception e)
            {
                e.getMessage();
            }
            finally {
                client.close();
            }
        }
        catch (Exception e)
        {
            e.getMessage();
        }
    }

    public interface OnMessageReceived {
        public void messageReceived(String message);
    }
}

This is how I call it from my main activity currently using a simple button to initiate the server to listen like this

btnStartServer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context,"Starting the server",Toast.LENGTH_LONG).show();
               TCPServer tcpServer = new TCPServer(new TCPServer.OnMessageReceived() {
                   @Override
                   public void messageReceived(String message) {
                      txtMessageReceived.setText(message);
                   }
               });
                tcpServer.start();

            }
        });

Now as for the C# or ASP.NET I have just added a simple button on webforms page to test things out and this is the code for that

        IPAddress ipAddress;
        IPEndPoint remoteEP;
        Socket sender;
        byte[] bytes;
  private void setUpSockets()
        {
            bytes = new byte[1024];
            try
            {
                ipAddress = IPAddress.Parse("192.168.0.102");
                remoteEP = new IPEndPoint(ipAddress, 11000);
                sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    sender.Connect(remoteEP);
                    byte[] msg = Encoding.ASCII.GetBytes("This is some Test <EOF>");
                    int byteSent = sender.Send(msg);
                    int byteRec = sender.Receive(bytes);
                    string messageRec = Encoding.ASCII.GetString(bytes, 0, byteRec);

                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                }
                catch (Exception e)
                {
                    string exception = e.Message;
                }
            }
            catch (Exception m)
            {
                string exception = m.Message;
            }
        }
  protected void Button1_Click(object sender, EventArgs e)
        {
            setUpSockets();
        }

Now I am just testing it before adding it to something meaningful but I am stuck at this int byteRec = sender.Receive(bytes); and I am not sure what should I do because as you can see I am trying to send some response from android client too. It is like it gets stuck at this line waiting for response which it never receives moreover the text box on the android side is not updating anything received as well.

DevX
  • 308
  • 5
  • 16

1 Answers1

0

I have been trying to find out the right way to do this but the issue was that I needed to be sure of the encoding of both languages and be sure to receive the bytes at either side before receiving the data. This question was very helpful and I was able to make the code work

The following changes were made and it worked

C# side

 bytes = new byte[1024];
            try
            {
                ipAddress = IPAddress.Parse("192.168.0.128");
                remoteEP = new IPEndPoint(ipAddress, 11000);
                sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    string toSend = TextBox1.Text;

                    sender.Connect(remoteEP);
                    //sending
                    int toSendLen = System.Text.Encoding.ASCII.GetByteCount(toSend);
                    byte[] toSendBytes = System.Text.Encoding.ASCII.GetBytes(toSend);
                    byte[] toSendLenBytes = System.BitConverter.GetBytes(toSendLen);
                    //Console.WriteLine("Soccket connected to{0}", sender.RemoteEndPoint.ToString());
                    sender.Send(toSendLenBytes);
                    sender.Send(toSendBytes);

                    //Receiving

                    byte[] rcvLenBytes = new byte[4];
                    sender.Receive(rcvLenBytes);
                    int rcvLen = System.BitConverter.ToInt32(rcvLenBytes, 0);
                    byte[] rcvBytes = new byte[rcvLen];
                    sender.Receive(rcvBytes);
                    String rcv = System.Text.Encoding.ASCII.GetString(rcvBytes);
                    TextBox1.Text = rcv;


                    //----------------OLD----------------------------
                    //  byte[] msg = Encoding.ASCII.GetBytes("This is some Test.");
                    //  TextBox1.Text = msg.ToString();
                    //  int byteSent = sender.Send(msg);
                    //  TextBox1.Text += "Bytes Sent = " + byteSent;

                    ////  System.Threading.Tasks.Task.Delay(1000).Wait();
                    //  int byteRec = sender.Receive(bytes);
                    //  string messageRec = Encoding.ASCII.GetString(bytes, 0, byteRec);
                    //  Console.WriteLine("Response from remote Device {0}", messageRec);
                    //  TextBox1.Text += "\nmessageRec = " + messageRec;
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            catch (Exception m)
            {
                Console.WriteLine(m.Message);
            }

Android Side

        ServerSocket serverSocket = new ServerSocket(11000, 10);
        Socket socket = serverSocket.accept();
        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();

        // Receiving
        byte[] lenBytes = new byte[4];
        is.read(lenBytes, 0, 4);
        int len = (((lenBytes[3] & 0xff) << 24) | ((lenBytes[2] & 0xff) << 16) |
                  ((lenBytes[1] & 0xff) << 8) | (lenBytes[0] & 0xff));
        byte[] receivedBytes = new byte[len];
        is.read(receivedBytes, 0, len);
        String received = new String(receivedBytes, 0, len); 
        // Sending
        String toSend = "Echo: " + received;
        byte[] toSendBytes = toSend.getBytes();
        int toSendLen = toSendBytes.length;
        byte[] toSendLenBytes = new byte[4];
        toSendLenBytes[0] = (byte)(toSendLen & 0xff);
        toSendLenBytes[1] = (byte)((toSendLen >> 8) & 0xff);
        toSendLenBytes[2] = (byte)((toSendLen >> 16) & 0xff);
        toSendLenBytes[3] = (byte)((toSendLen >> 24) & 0xff);
        os.write(toSendLenBytes);
        os.write(toSendBytes);

        socket.close();
        serverSocket.close();

The above mentioned android code was updated in TCPServer class in the method run.

Community
  • 1
  • 1
DevX
  • 308
  • 5
  • 16