客户端不从服务器的DataOutputStream接收输出

时间:2013-02-04 04:20:38

标签: java networking tcp dataoutputstream

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

SERVER:

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 "";
}

2 个答案:

答案 0 :(得分:3)

客户端正在调用readLine()但是服务器没有写一行,只是字节,所以客户端正在等待行终止符。将'\ n'附加到服务器的回复中。此外,服务器应在完成后关闭已接受的套接字。通过关闭围绕它的任何编写器或输出流来完成此操作,而不是关闭套接字本身。

您应该使用BufferedOutputStream代替DataOutputStream。它将适用于简单数据,但如果您迟早不修复它,则可能会出现问题。通常,您应始终使用对称输入和输出流或读取器。

答案 1 :(得分:0)

1)您应该关闭或清除outToServer / outToClient

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