2

我目前正在尝试编写我的第一个客户端>服务器系统来通过网络来回传输包含字符串的数据包。但是我遇到了以下问题:客户端向服务器发送消息,服务器接收消息,处理消息,然后应该向客户端发送回复,但客户端从未收到此消息并且挂起等待来自服务器的响应。这是代码:

服务器:

public static void handlePackets() throws Exception {
    String clientSentence;
    String returnToClient;
    ServerSocket welcomeSocket = new ServerSocket(1337);

         System.out.println("Packet receiver initialized!");
         while (run) {
            Socket connectionSocket = welcomeSocket.accept();
            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            clientSentence = inFromClient.readLine();
            System.out.println("Received Packet: " + clientSentence);


            System.out.println("Compiling return to client.");
            returnToClient = "";
            if (clientSentence.startsWith("Handshake-")) {
                returnToClient = handleHandShake(clientSentence);
            }

            outToClient.writeBytes(returnToClient);
            System.out.println("Sent client response " + returnToClient);
         }
         welcomeSocket.close();
  }

客户:

public static String sendTCP(String host, String content) {
    try {
        System.out.println("Packet sender sending TCP packet " + content);
        String serverResponse;
        Socket clientSocket = new Socket(host, 1337);
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        outToServer.writeBytes(content + '\n');

        System.out.println("Send data to sever. Awaiting response.");

        serverResponse = inFromServer.readLine();
        clientSocket.close();

        System.out.println("Server response received " + serverResponse + " result was returned to caller.");

        return serverResponse;
    } catch (Exception e) {
        e.printStackTrace();
    }


    return "";
}
4

2 回答 2

3

客户端正在调用readLine(),但服务器没有写一行,只是字节,所以客户端永远等待行终止符。将“\n”附加到服务器的回复中。服务器也应该在完成后关闭接受的套接字。通过关闭您包裹在它周围的任何编写器或输出流来做到这一点,而不是通过关闭套接字本身。

您应该使用BufferedOutputStream而不是DataOutputStream. 它适用于简单的数据,但如果您迟早不修复它,您可能会遇到字符集问题。一般来说,您应该始终使用对称的输入和输出流或读取器。

于 2013-02-04T04:50:00.433 回答
0

1)您应该关闭或刷新 outToServer / outToClient

2)当您使用 BufferedReader 阅读时,您应该使用 BufferedWriter 而不是 DataOutputStream 来编写

于 2013-02-04T04:29:15.730 回答