我正在制作一个Minecraft模组,其中我想要在后台运行一个套接字服务器,等待来自Python客户端的消息。
服务器在一个线程中运行。
以下是我启动线程的代码:
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
InterPythonJavaCommunicatorServer.begin(socket, sockIn, sockOut);
}catch (IOException e){
System.out.println("Woah! Somethings gone wrong! ringing a alarm now!");
}
}
});
t.start();
t.join();
整个Server类
package com.satyamedh.minecraft_ai_helper.communicator;
import com.satyamedh.minecraft_ai_helper.Movement;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.net.Socket;
public class InterPythonJavaCommunicatorServer{
public static void begin(Socket socket, BufferedReader sockIn, BufferedWriter sockOut) throws IOException {
boolean done = false;
while (true) {
System.out.println("Test!");
boolean ready = sockIn.ready();
if(!ready) {
return;
}
try {
String response = sockIn.readLine(); // Stops Here!
System.out.println(response);
//if (response == null) {
//System.out.println("Remote process closed the connection.");
//done=true;
//}
if (response.equals("forward\n")){
boolean o = Movement.forward(1);
if (o){
sockOut.write("done");
sockOut.flush();
}
}
} catch (IOException e) {
System.out.println("Welp! ALARM BOI!");
}
}
}
}
我已经对整个代码进行了断点调试,似乎停在了
String response = sockIn.readLine();
这一行上。并且 Test!
消息只运行了一次。PS:我已经搜索了几个小时,但为什么会出现这种情况我还是找不到相关的信息!
我知道这可能非常愚蠢,很容易被抓住 :)
编辑:正如@DevParzival所说,我尝试使用
t.join();
,但仍然是同样的情况!我已经编辑了上面的代码以匹配我的当前代码。编辑2:这是客户端代码(Python)
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("", 1243))
server_socket.listen(5)
print(
"TCPServer Waiting for client on port 1243")
while 1:
client_socket, address = server_socket.accept()
print(
"I got a connection from ", address)
while 1:
data = input("SEND( TYPE q or Q to Quit):")
if data == 'Q' or data == 'q':
client_socket.send(bytes(data, encoding='utf8'))
client_socket.close()
break
else:
client_socket.send(bytes(data, encoding='utf8'))
data = client_socket.recv(512)
if data == 'q' or data == 'Q':
client_socket.close()
break
else:
print("RECEIVED:", data)
提前感谢。
sockIn
?你是如何向它传递数据的? - AmongalenNewLine | CHR(10) | \n
字符,如果使用socketIn.readLine()
,它会等待行分隔符才返回。 - Whome