Fatemeh M. Rezaie
Fatemeh M. Rezaie

Reputation: 163

Communicating android and windows through socket

I want to make my android app open socket to my windows console app and they communicate with each other. The socket is opened and data is sent and received in windows app, but my android app does not receive the answer which sent by windows. I watch the packets in my android and I saw the packets are coming but I do not know why my app do not receive it!

windows app server class:

class Server
{
    private TcpListener tcpListener;
    private Thread listenThread;

    public Server()
    {
        Console.WriteLine("\nStarting server...");

        this.tcpListener = new TcpListener(IPAddress.Any, 1234);
        this.listenThread = new Thread(new ThreadStart(ListenForClients));
        this.listenThread.Start();
    }

    private void ListenForClients()
    {
        Console.WriteLine("\nWaiting for clients to connect...");

        this.tcpListener.Start();

        while (true)
        {
            //blocks until a client has connected to the server
            TcpClient client = this.tcpListener.AcceptTcpClient();

            //create a thread to handle communication with connected client
            Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
            clientThread.Start(client);
        }
    }

    private void HandleClientComm(object client)
    {
        Console.WriteLine("\nIncoming from client...");

        TcpClient tcpClient = (TcpClient)client;
        NetworkStream clientStream = tcpClient.GetStream();

        byte[] message = new byte[4096];
        int bytesRead;

        try
        {
            while (true)
            {
                bytesRead = 0;

                try
                {
                    //blocks until a client sends a message
                    bytesRead = clientStream.Read(message, 0, 4096);
                }
                catch
                {
                    //a socket error has occured
                    break;
                }

                if (bytesRead == 0)
                {
                    //the client has disconnected from the server
                    break;
                }

                //message has successfully been received
                ASCIIEncoding encoder = new ASCIIEncoding();
                Console.WriteLine("\nReceived: \n\n" + encoder.GetString(message, 0, bytesRead));

                //By FMR
                string response = "random responsive: " + new Random().Next(1000).ToString() + "\n";//"\r\n";
                //writeData(clientStream, response);

                byte[] msg = System.Text.Encoding.ASCII.GetBytes(response);

                // Send back a response.
                clientStream.Write(msg, 0, msg.Length);
                clientStream.Flush();

                Console.WriteLine("\nResponed ..." + response);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("\nException while: " + ex.Message);
        }
        tcpClient.Close();
      }
   }

my android thread:

Thread thread = new Thread(new Runnable() {

@Override
public void run() {
    Socket socket = null;
    ServerSocket serverSocket = null;
    Boolean bRun = true;
    try {
        socket = new Socket(ip, port);

        if(outputStream == null) {
            outputStream = new DataOutputStream(socket.getOutputStream());
        }


        // become server
        serverSocket = new ServerSocket(port);
        Log.i(G.TAG, "before serverSocket.accept");
        socket = serverSocket.accept();
        Log.i(G.TAG, "response recieve: ");

        inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }
    catch (Exception e) {
        try {
            serverSocket.close();
        } catch (IOException e1) {
            Log.e(G.TAG, "serverSocket.close() e: " + e1.getMessage());
        }
        try {
            socket.close();
        } catch (IOException e1) {
            Log.e(G.TAG, "socket.close() e: " + e1.getMessage());
        }
    }
    Log.i(G.TAG, "after start recieve: ");
    while (bRun) {
        try {
            Log.i(G.TAG, "while start: ");
            String message = inputStream.readLine();
            Log.i(G.TAG, "response message: " + message);
            if (message != null) {
                setListMessage(false, message);
            }
        }
        catch (IOException e) {
            bRun = false;
            Log.e(G.TAG, "while bRun e: " + e.getMessage());
        }
    }
}
});
thread.start();

// in another function, my message is sent successfully from android and receive in windows

Upvotes: 1

Views: 895

Answers (1)

Fatemeh M. Rezaie
Fatemeh M. Rezaie

Reputation: 163

I found the problem, this line

socket = serverSocket.accept();

made the problem when I comment the line, the android app received the response!

Does anybody know why?

Upvotes: 1

Related Questions