Java Chat Program
Java Chat Program
Introduction
In this edition of Objective Viewpoint, you will learn how to develop a simple chat system. The
program will demonstrate some key Java programming techniques including I/O, networking,
and multithreading.
ChatServer Code
Listing 1 shows the code for the ChatServer class. The class has only one method, main(). The
first three lines declare three variables: port, serverSocket, and socket. The port variable
stores the port on which the server will listen for new connections. The default value for the port
in this example is 9800. In the first try/catch block, we determine if the user passed any
parameters. If so, we attempt to parse the first command line parameter (the only one we care
about in this case) using the Integer.parseInt method. If the string does not represent an
integer, then a NumberFormatException will be thrown. The catch block simply specifies
proper program usage and exits.
In the second try/catch block, the chat server attempts to create a new server socket and begin
to accept connections. First, a new ServerSocket object is created with a specific port. The code
then enters an endless loop, continuously accepting connections and creating new chat client
handlers. The ServerSocket.accept() method waits forever until a new connection is
established. When a new connection is detected, a Socket object is created inherently and
returned. A new ChatHandler object is then constructed with the newly created socket. Since the
ChatHandler is a Thread, we must call the start method to make the chat client code run.
If anything goes awry with either the server socket or client socket, an IOException will be
thrown. In this example, we simply print the stack trace. In the finally block, we attempt to
close the server socket connection since the loop has been exited.
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ChatServer {
public static final int DEFAULT_PORT = 9800;
public static void main(String[] args) {
int port = DEFAULT_PORT;
ServerSocket serverSocket = null;
Socket socket = null;
try {
if(args.length > 0)
port = Integer.parseInt(args[0]);
} catch(NumberFormatException nfe) {
System.err.println("Usage: java ChatServer [port]");
System.err.println("Where options include:");
System.err.println("\tport the port on which to listen.");
System.exit(0);
}
try {
serverSocket = new ServerSocket(port);
while(true) {
socket = serverSocket.accept();
ChatHandler handler = new ChatHandler(socket);
handler.start();
}
} catch(IOException ioe) {
ioe.printStackTrace();
} finally {
try {
serverSocket.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
}
ChatHandler Code
The ChatHandler code is shown in Listing 2. In the constructor, we assign the socket the
handler we will use and construct the socket input and output streams. The BufferedReader and
PrintWriter classes are used for handling user I/O. The Reader classes enable proper handling
of bytes and characters. For example, the BufferedReader class method readLine() will
properly convert 8-bit bytes to 16-bit UNICODE characters.
The following line constructs a new BufferedReader object:
java.io.BufferedReader;
java.io.InputStreamReader;
java.io.IOException;
java.io.OutputStreamWriter;
java.io.PrintWriter;
java.net.Socket;
java.util.Vector;
Editor's Note: Many thanks to Dick Seabrook for finding and correcting some errors in the
above code listing 2.
Summary
In this article, you learned how to use the standard Java networking and I/O classes, and also
how to handle concurrent I/O safely using threads. As an exercise, try creating a chat GUI, and
also expand the current programs to include identifiable users and user groups.