TCP客户端发送但未接收和服务器接收但未发送

时间:2014-01-21 10:13:03

标签: java tcp

我用Java创建了一个程序,允许服务器管理员监视客户端进程。当我将数据发送到服务器时,一切都OK。但是,当我尝试发送数据时,它只是没有收到它。

import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception {
    String clientSentence;
    String capitalizedSentence;
    ServerSocket welcomeSocket = new ServerSocket(6789);
    while (true) {
        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: " + clientSentence);
        capitalizedSentence = clientSentence.toUpperCase();
        outToClient.writeBytes(capitalizedSentence);
    }
}

}

我发现了错误,我没有在邮件后发送“\ n”,导致堆积,而且从未发送过。

import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception {
    String clientSentence;
    String capitalizedSentence;
    ServerSocket welcomeSocket = new ServerSocket(6789);
    while (true) {
        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: " + clientSentence);
        capitalizedSentence = clientSentence.toUpperCase() + "\n"; // <-----
        outToClient.writeBytes(capitalizedSentence);
    }
}

}

1 个答案:

答案 0 :(得分:1)

您的服务器实际上从未完成发送线路。它发送“killpr”然后永久地离开套接字 - 不发送换行符或关闭套接字。

在客户端上,readLine不会返回,因为它正在等待该行的其余部分。