我在服务器端使用此线程来从客户端接收字符串:
int clientNumber = 0;
ServerSocket listener = new ServerSocket(6543);
try {
while (true) {
new Capitalizer(listener.accept(), clientNumber++).start();
}
} finally {
listener.close();
}
...
private static class Capitalizer extends Thread {
private Socket socket;
private int clientNumber;
public Capitalizer(Socket socket, int clientNumber) {
this.socket = socket;
this.clientNumber = clientNumber;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
String input = in.readLine();
System.out.println("Am Server: " + input);
out.println(input.toUpperCase());
}
} catch (IOException e) {
e.printStackTrace();
}
客户端看起来像这样:
try {
Socket client = new Socket("localhost", 6543);
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.print("Enter something : ");
String input = br.readLine();
out.write(input.getBytes());
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
我不清楚服务器端没有收到字符串。 我在 Eclipse 控制台中输入一个字符串,在客户端,该字符串被发送到服务器,但在服务器端没有任何反应。 有人提示我做错了什么吗?
最佳答案
您的服务器期望接收行,因此您的客户端必须发送行。但您的客户端不发送线路。为什么?
来自docs :
Return Value
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached.
因此,readline
的返回值不是一行,因为,正如同一页面所说:
A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
为了避免将来出现此错误,在使用 TCP 之前,以书面形式准确指定将发送和接收的信息。如果您使用 TCP 交换消息,请在字节级别精确定义消息是什么。
对于此应用程序,您应该精确指定消息将由一系列字符组成,不包括任何行结束符,其结尾标记为行结束符。这清楚地表明客户端存在错误,因为它显然没有按照协议(protocol)指定发送消息。
关于Java TCP IP 连接 - 服务器上没有任何显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42725954/