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

时间:2013-02-04 09:51:44

标签: c# java client-server

我在C#编写了一个异步服务器,用Java编写了一个TCP客户端和一个Android应用程序。客户端可以很好地向服务器发送消息,并在发送消息时收到消息。但是,当我从服务器向客户端发送消息时,客户端仅在服务器关闭后(即套接字关闭时)显示消息。 奇怪的是,我也在C#中编写了一个客户端,并在收到消息后立即收到消息。

C#服务器和客户端都使用异步begin *和end *方法,Java客户端使用流读取器/写入器。

任何人都可以建议为什么Java客户端会以这种方式运行以及如何解决这个问题?

感谢。

客户代码:

    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);

    }

}

服务器代码:

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());
        }
    }

1 个答案:

答案 0 :(得分:1)

我的猜测是,您从服务器发送的数据不会以EOL序列(\n\r\n)结束。因此,客户端的readLine()方法永远不会返回,因为它只能在确定线路终止时(即接收到EOL序列或连接关闭时)返回。