Java Socket Server与Python客户端的通信,程序不会输入“inputLine = in.readLine()” - 循环
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java Socket Server与Python客户端的通信,程序不会输入“inputLine = in.readLine()” - 循环相关的知识,希望对你有一定的参考价值。
我正在尝试用Java创建一个可以与python客户端通信的套接字服务器。我遇到的问题是,如果我启动服务器,通过python发送消息,然后立即退出,一切都正常,但如果客户端发送消息然后再次侦听套接字,服务器将不会响应。
这是代码,主要来自this example from oracle
public class PrimeServer {
public static void main(String[] args) throws IOException {
int portNumber = 4444;
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()))
) {
String inputLine;
String outputLine;
String rawMessage;
// Initiate conversation with client
PrimeProtocol ppc = new PrimeProtocol();
outputLine = String.format("%1022s", "Ready").replace(' ', '0');
out.println(outputLine);
System.out.println("Over while");
while ((inputLine = in.readLine()) != null) {
System.out.println("In while");
if (ppc.processInput(Integer.parseInt(inputLine))){
rawMessage = "True";
} else {
rawMessage = "False";
}
outputLine = String.format("%1024s", rawMessage).replace(' ', '0');
System.out.println("Outputting " + rawMessage);
out.println(outputLine);
}
System.out.println("Passed while.");
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
和python代码的好措施:
msg_len = 1024
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("127.0.0.1", 4444))
init_message = sock.recv(msg_len).decode("UTF-8")
init_message = init_message.replace('0', '')
print(init_message)
print(len(init_message))
sock.send(b'3')
使用此代码,java服务器的输出是:
Over while
In while
Outputting True
Passed while.
客户端输出是:
1024
Ready
之后连接断开。
但是如果我将这一行添加到客户端:new_message = sock.recv(msg_len).decode("UTF-8")
制作新的python:
msg_len = 1024
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("127.0.0.1", 4444))
init_message = sock.recv(msg_len).decode("UTF-8")
print(len(init_message))
init_message = init_message.replace('0', '')
print(init_message)
sock.send(b'3')
new_message = sock.recv(msg_len).decode("UTF-8")
服务器卡住并且输出仅为:
Over while
客户输出:
1024
Ready
同时也是干扰。
有什么想法在这里发生了什么?
答案
原来它是需要刷新的python套接字。新的python代码:
msg_len = 1024
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("127.0.0.1", 4444))
init_message = sock.recv(msg_len).decode("UTF-8")
print(len(init_message))
init_message = init_message.replace('0', '')
print(init_message)
sock.send(b'3
')
new_message = sock.recv(msg_len).decode("UTF-8")
print(new_message)
(添加 n)消息传出。
以上是关于Java Socket Server与Python客户端的通信,程序不会输入“inputLine = in.readLine()” - 循环的主要内容,如果未能解决你的问题,请参考以下文章
python socket 实现简单client与server
mb server指令与socket tool仿真测试连不上