Single thread for Multi User?

Currently I use 1 thread for each client that connects to a game or chat system. I just realized how easier it would be for me to maintain code, add new features or to update the systems if I used 1 thread for communicating with the clients instead of 1 thread for each client.

Currently I use this code to connect each client to the main program…


public void run(){ 
	while(true){
		try{
			//Find next free Conn number
    		setConn();
			nt1[Conn] = new NetConn(serverSocket.accept(), Conn);
    		
		}catch(IOException e){
			System.out.println(e);
		}

		try {
			t.sleep(10);
		} catch (InterruptedException e) {
			System.out.println(e);
			stop();
		}
	}
}

This creates multiple threads and assigns each a variable I can use in the main program for passing data back and forth.

If I wanted to use 1 thread, this try loop would catch a connecting client and open a socket between that client and the existing thread that is already there. The problem is, I have no idea how to do this. Anyone have any pointers on this?

Any help would be greatly appreciated!

When you want your networking in one thread, you’re only option is java.nio (or some framework based on that).

NIO is basically a can of worms, compared to plain old Socket/ServerSocket.

I’d highly recommend you not to switch to NIO, maybe look around for more highlevel frameworks (like JGN or MINA). IMHO it’s best to just make it work with java.io and learn from it.

It all those threads make you feel uncomfortable, simply pass all your received data in 1 ‘global inbound queue’, that is drained by 1 thread. Also put all data you intend to write in an ‘outbound queue’ per connection.

Now you have the benefits of an easy to grasp networking API, with the simplicity of 1 thread that handled all networking data.

Thank you very much! Exactly the information I needed to know. I really appreciate the help there!

Thank you!