我一直在尝试在 Java 客户端套接字和 Python 服务器套接字之间发送一个简单的字符串。这是服务器套接字的代码:
HOST=''
PORT=12000
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADRR,1)
s.bind((HOST,PORT))
s.listen(5)
device=variador()
while True:
conn,addr=s.accept()
if data=="turn_on":
respuesta=device.send_order(variador.start_order)
conn.send(respuesta+'\n')
conn.close()
客户端代码是:
try {
Socket socket = new Socket("192.168.10.171", 12000);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
out.print(command);
out.close();
in.close();
socket.close();
} catch (UnknownHostException e) {
System.err.println("Unknown Host.");
// System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection.");
// System.exit(1);
}
一切正常,直到我尝试使用以下命令读取服务器的响应:
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
然后代码挂起,Python 服务器不会收到任何信息,我使用 print 对此进行了测试。
在Java客户端中尝试先发送然后等待服务器的响应是否有问题?
任何帮助都感激不尽。