简体   繁体   English

Java TCP客户端和C#服务器; 服务器关闭后,客户端仅收到消息

[英]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. 我已经用C#编写了一个异步服务器,并用Java和一个Android应用程序编写了一个TCP客户端。 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. 奇怪的是,我也用C#编写了一个客户端,并且在发送消息后立即接收消息。

The C# server and client both use the asynchronous begin* and end* methods and the Java client uses a stream reader/writer. C#服务器和客户端都使用异步begin *和end *方法,而Java客户端使用流读取器/写入器。

Can anyone please suggest why the Java client is behaving in this way and how to remedy this? 任何人都可以提出为什么Java客户端以这种方式运行以及如何对此进行补救的建议吗?

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 ). 我的猜测是,您从服务器发送的数据没有以EOL序列( \\n\\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). 因此,客户端的readLine()方法永远不会返回,因为它只能在确定行终止时(即,在收到EOL序列或关闭连接时)返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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