我正在尝试让服务器(用Python编写)和客户端(用Java编写)进行通信。服务器代码如下:
import socket # Import socket module
connection=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection.bind(('',12800))
connection.listen(5)
connection_with_client, info_connection = connection.accept()
msg=b""
while(msg!=b"stop"):
print("Entering loop")
msg = connection_with_client.recv(1024)
connection_with_client.send(b"This is a message")
print("Sent")
connection_with_client.close()
connection.close()
客户端代码是:
try {
socket = new Socket(InetAddress.getLocalHost(),12800);
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.print("stop");
out.flush();
System.out.println("Sent");
in = new BufferedReader (new InputStreamReader (socket.getInputStream()));
String message_from_server = in.readLine();
System.out.println("Received message : " + message_from_server);
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
奇怪的是:当客户端发送消息“stop”时,一切正常,来自服务器的消息被客户端收到。现在,当客户端发送另一条消息而不是“stop”时,服务器告诉它已经发送了该消息,并再次进入循环,但是客户端从未收到该消息并卡在 in.readLine() 指令处。
我真的不明白为什么循环中的第一段在两种情况下应该具有相同的效果...欢迎任何帮助!
最佳答案
在客户端,您正在使用readLine
。显然,这会读取该行,但它如何检测该行的结束位置呢?答案是:
您的服务器应该将行结尾附加到您发送给客户端的所有消息中。
尝试附加 b'\r\n'
或操作系统上的任何行尾。只要在客户端调用 readLine
,您应该附加客户端的行结尾,而不是服务器操作系统。
对于 Windows,它是 b'\r\n'
对于 Linux b'\n'
关于java - 仅当服务器执行循环时,套接字客户端才不会从服务器接收消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53542214/