因此,我正在用 Java 制作一个聊天服务器,以摆脱对 Hamachi 在我的 Minecraft 服务器中托管和通信的依赖。它完美地工作,除了一件事:我无法弄清楚如何向服务器添加命令。我的主循环如下:
/*Executed in constructor*/
public void listen(int port) throws IOException {
//Initialize the ServerSocket
ss = new ServerSocket(port);
System.out.println("Listening on " + InetAddress.getLocalHost() + ":" + ss.getLocalPort());
running = true;
//Keep accepting connections
while (running) {
//Get the incoming connection
Socket s = ss.accept();
System.out.println("Connection from: " + getFullIP(s));
//Create a DataOutputStream for writing data to the other side
DataOutputStream dataOut = new DataOutputStream(s.getOutputStream());
//Save this stream so I don't have to make it again
outputStreams.put(s, dataOut);
//Create a new thread for this connection
new ServerThread(this, s);
if (!running) {
stop();
}
Scanner cmdScanner = new Scanner(System.in);
String command = cmdScanner.next();
processCommand(command);
}
}
此代码的结果是,在客户端连接到服务器之前,我无法键入命令(因为ss.accept()
)。在我执行命令之前,客户端无法连接(cmdScanner.next()
)。我该如何解决这个问题?