Create your own chat box in Java18 min read

The code contains 5 classes that you can cut & paste in a directory on your PC and it should work.

The 5 classes are:

  • –
  • –
  • –
  • –
  • –

You can start the Server by typing
> java Server
at the console prompt. That will execute it in console mode and the server will wait for connection on port 1500. To use another port pass the port number to use as first parameter to the command
> java Server 1200
will ask the Server to listen on port 1200.
You can use <CTRL>C to stop the server.

The Client class.

Once the Server is started you can start the Client by typing
> java Client
at the console port. That will start the Client with the username Anonymous on the localhost using port 1500. So the command is equivalent to
> java Client Anonymous 1500 localhost
You can specify any of the parameter in order
> java Client Me == > java Client Me 1500 localhost
> java Client Me 1200 == > java Client Me 1200 localhost
> java Client Me 1200 == > java Client Me 1200

Once the Client started in console mode you can enter:
– LOGOUT to logout and close the connections
– WHOISIN to receive the list of the user connected to the server
– anything else is a message that will be broadcast, with your username, to all the Clients on the room

The GUI is a simple GUI using JTextArea don’t expect fancy fonts, colors, Icons,… I kept it as simple as possible.

The ClientGUI class.

This is a simple GUI. It is a BorderLayout with in the NORTH region an editable JTextField containing the port number the Server should listen to and 2 buttons to Start/Stop the Server.
The CENTER region contains two JScrollPane both containing a JTextArea. The first JTextArea contains the messages exchanged in the ChatRoom, basically what the Clients see. The secong JTextArea contains event messages: who login, who logout, error messages, and so on
To execute that GUI type
> java ServerGUI
at the console prompt


The ClientGUI class.

This is the GUI for the Client. Also a BorderLayout. In the NORTH region two JTextField to enter the host name of the Server and the port number it is listening to.
The CENTER region contains a JScrollPane with a JTextArea that contains the messages exchanged in the ChatRoom.
The SOUTH region conatisn 3 buttons: “Login”, “Logout”, “Who is in”.

To start the Client type
>java ClientGUI
at the command prompt

Leave a Comment