[英]Java Socket Server Communication to Python client, program won't enter “inputLine = in.readLine()”-loop
我正在嘗試用Java創建可以與python客戶端通信的套接字服務器。 我遇到了一個問題,如果我啟動服務器,通過python發送一條消息,然后立即退出,那么一切運行正常,但是如果客戶端發送一條消息,然后再次監聽套接字,服務器將不會響應。
這是代碼,主要來自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\n')
new_message = sock.recv(msg_len).decode("UTF-8")
print(new_message)
(在\\ n后面添加了)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.