0

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

1 回答 1

1

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

于 2013-02-04T10:14:41.407 回答