简体   繁体   中英

Java TCP Client and C# Server; Client Only Receives Message After Server Closes

I have written an asynchronous server in C# and a TCP client in Java for and an Android app. The client can send messages fine to the server and they are received when they are sent. However when I send a message from the server to the client, the client only displays the message after the server is shutdown (ie when the socket closes). The strange thing is that I have written a client in C# as well and that receives messages as soon as they are sent.

The C# server and client both use the asynchronous begin* and end* methods and the Java client uses a stream reader/writer.

Can anyone please suggest why the Java client is behaving in this way and how to remedy this?

Thanks.

Client Code:

    public void run() {

    mRun = true;

    try {
        //here you must put your computer's IP address.
        InetAddress serverAddr = InetAddress.getByName(SERVERIP);

        Log.e("TCP Client", "C: Connecting...");

        //create a socket to make the connection with the server
        socket = new Socket(serverAddr, SERVERPORT);

        try {
            if (out != null)
            {
                //send the message to the server
                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

                Log.e("TCP Client", "C: Sent.");

                Log.e("TCP Client", "C: Done.");
            }

            //receive the message which the server sends back
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            //in this while the client listens for the messages sent by the server
            while (mRun) {
                serverMessage = in.readLine();

                if (serverMessage != null && mMessageListener != null) {
                    //call the method messageReceived from MyActivity class
                    mMessageListener.messageReceived(serverMessage);

                    serverMessage = null;
                }
            }

            Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");

        } catch (Exception e) {

            Log.e("TCP", "S: Error", e);

        } finally {
            //the socket must be closed. It is not possible to reconnect to this socket
            // after it is closed, which means a new socket instance has to be created.
            socket.close();
        }

    } catch (Exception e) {

        Log.e("TCP", "C: Error", e);

    }

}

Server Code:

public void Send(String data)
    {
        // Convert the string data to byte data using ASCII encoding.
        byte[] byteData = Encoding.ASCII.GetBytes(data);

        // Begin sending the data to the remote device.
        socket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), socket);
    }

    private static void SendCallback(IAsyncResult ar)
    {
        try
        {
            //Retrieve the socket from the state object.
            Socket clientSocket = (Socket)ar.AsyncState;

            //send the data
            int bytesSent = clientSocket.EndSend(ar);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

My guess is that the data you send from the server doesn't end with an EOL sequence ( \\n or \\r\\n ). So the readLine() method at client-side never returns, since it can only return when it's sure the line is terminated (ie when an EOL sequence is received, or the connection is closed).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM