Code your own chat network.
Darren Yates combines Java threads and networking to create a chat client and server that combines to build your own home chat network.
Facebook Messenger, Google Chat, Twitter — real-time chat systems are among the most popular apps ever developed. They’re not just cool for chatting to another person, they’re great for chatting with a whole group of people. So this month, we’re combining almost everything we’ve learned about Java programming over the last year to create a complete private chat network, consisting of separate client and server apps.
GET THE SOURCE CODE
You’ll find the source code for this month’s project on our website at apcmag.com/magstuff. You’ll also find two .jar (Java Archive) files — HomeChatServer.jar and HomeChatClient.jar. These are run-time files — you just need the Java Runtime Environment (JRE) preinstalled on each machine, doubleclick on the appropriate JAR file and you’re away. You can download the latest JRE from Oracle’s website at tinyurl.com/apc429-jre. To edit the source code, grab the NetBeans IDE and Java SE Software Development Kit Bundle from Oracle at tinyurl.com/ apc429-bundle.
Unzip the outer source code zip file, launch NetBeans, select ‘File > Import Project > From ZIP’ and choose either of the inner project zip files.
HOW IT WORKS
Our ‘Home Chat Network’ is designed to work on a local-area network (LAN), such as that found in most homes, with multiple PCs connected up, either using wired or wireless tech, to a single ADSL or cable modem connected to the Internet.
The chat system itself consists of two parts — a server app that acts as the central distribution box for all chat messages; plus the client app, which runs on each PC connected to the LAN. Any client can send a message to the chat network and that message is distributed to every other client on the chat network via the server. Think of the server app as the hub of a bicycle wheel with clients at the outer rim.
It sounds straightforward, but under the bonnet, we’re taking the Java networking we started with last month and combining it with Java threads to enable multiple Java apps to communicate with each other in real time. That makes things a little more complicated.
SETTING UP THE PCS
This is the straightforward bit. To run the chat system, first launch the Home Chat Server app (HomeChatServer.jar) on the PC you want to be the server. Next, launch HomeChatClient.jar, the client app, on each of the client systems you want sending and receiving messages (this can include the server PC itself). Provided they’re hooked into your home network, the whole thing should now be ready to go.
CHAT SERVER CODE
We’ll start with the chat server app. The GUI (graphical user interface) here is nothing more than a jTextArea sitting inside a jScrollPane. It logs all activity from the clients as they connect and disconnect, along with the messages they send. The tricky stuff is in how the server actually does its work.
Look at the ‘HomeChatServer()’ constructor and the first few lines set up the interface and title text. After that, we get to the ‘try{}’ statement; it’s the code here that drives what goes on.
It starts with appending some basic welcome text to the serverStatus jTextArea, followed by creating the server socket with the port number ‘3801’.
Next comes a seeminglyodd line — ‘while (true)’. The ‘while()’ function works by continuing to loop through the statements inside the loop until the Booleanconditional statement inside the brackets evaluates to ‘false’. But since ‘true’ is always true, we’re just saying ‘loop this code forever’.
That code begins with the server waiting for a client to request a connection via the ‘serverSocket. accept()’ statement. Remember, Java waits at this statement until a client pings in. Once a client app does so, the new socket connection created is assigned to a Socket object called ‘chatSocket’, which then gets added to an ArrayList of chat sockets called (appropriately) ‘chatSockets’.
Put another way, we’re creating a great big telephone book of clients and, each time a new client connects, its socket connection ‘phone number’ is stored in our phonebook.
So now we’ve established a socket connection with the client, we next create a new DataOutputStream object that allows us to send messages direct to that client.
After that, we send some basic data to the client — first, we increment the static ‘clientNo’ integer variable and send that, then we send the size of the chatClients ArrayList. Why? The ‘clientNo’ variable tells each client which number it is in the list and the size of the ArrayList tells the user how many clients are currently connected. Next, the following three ‘append’ statements document the new client’s arrival to the server’s serverStatus textarea, including hostname and IP address.
“A client can send a message at any time — the server has no idea when, but it needs to be ready and waiting for when it does.”