Simple Chat One.

Written by Sean R. Owens (sean at guild dot net). Share and enjoy.

This example assumes basic familiarity with Java, especially with how to compile and run programs. If you need help compiling and running these, don't ask me. Go somewhere else. (I suggest the IRC channel #java on - they just love simple questions like those.)

For an introduction to the basics of sockets, see SocketExample.

The earlier socket examples were all fine and good, but they really didn't go far enough. Once you have a java program talking to multiple sockets at the same time, what do you do with it?

In an earlier example, we ended up with what was essentially an echo server capable of handling multiple connections at once. Other programs could open a socket to our server, and send data across the socket, and the server would send the same data back across the socket to the program that sent it. Many sockets could be opened and send data back and forth without having to wait for the server to finish dealing with the other sockets.

But none of the connections could interact with each other. None of the data being sent back and forth was going to anyone other than the server and the program that originally sent it. Making the different socket connections be able to interact means getting into thread synchronization issues.

Lets take our earlier server and turn it into a chat server.

1.0 A Simple Chat Server (source, 57 lines)

This is almost the same as SimpleServer in the earlier example. The key difference is that when a new handler is created (for each new socket connection) Server also passes in a reference (the same each time - Server creates one instance of Switchboard) to a switchboard object, and writes a "message of the day" to the new connection. (source, 117 lines) (source, 62 lines)

Last modified: Wed May 27 19:16:42 EDT 2009