So I’m making a chat server in Java to kind of move out of depending on Hamachi for hosting and communication in my Minecraft server. It works perfectly, except for one thing: I can’t figure out how the life of me how to add commands to the server. My main loop goes as follows:
/*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);
}
}
The result of this code is that I cannot type a command until a client connects to the server (because of ss.accept()). Until I execute a command, a client cannot connect (cmdScanner.next()). How do I get around this?
I think that your command processor should be in an other thread. IMHO a server should always have a thread which only job is to receive new connection and dispatching it. Processing your input should be part of an other thread.