Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Creating a Multithreaded Chat with Socket in Java

See in this article how to create a multithreaded chat with Java. For this you need to use and apply concepts of Thread and Socket, as well as Object Oriented Programming

A thread can be considered a sequential flow of control within a program where we give some job and she performs, providing higher performance. Programming is very important to know how to apply forms of asynchronous processing, because we currently have highly fast processors and do not know how to exploit them properly. In our chat we will create in this article, the thread will be used to control the flow of messages sent and received by a customer, because imagine if all they were stored in a queue and processed only by a thread: the service would be precarious and probably no one would use.

What is Socket

Socket is a medium used to enable the client/server connection, where a client tells the IP address and the corresponding server port. If it accepts the connection, it will create a means of communication with the client. Therefore, the combination of threads and Socket is perfect for implementing a chat.


Front the amount of object-oriented languages (OO) exist, such as C #, C ++, Java, among others, it is clear that to master them you need to fully understand the OO pillars, as Heritage (per interface and per class), Encapsulation, polymorphism and Abstraction. While mastering these subjects, will surely find it easier to build simple and quality codes with low coupling and high cohesion. In this article we depararemos us with Heritage for interface and base class, abstraction and encapsulation, but will not be the focus of the same address their concepts.

The following describes the responsibilities and behaviors of and classs used to build the Chat:

  • Responsibility and behaviors the server will serve as a centralized unit of all incoming connections via socket and will have the responsibility to send a message (received from a customer) to all the other connected to the server. When a client connects to it it creates a thread for that customer, that is, each connection will have its respective thread and the server will manage it;
  • Responsibility and behaviors Each user creates an instance of the client and make a connection to the server socket. The client must inform the address of the server socket and its port, so you must run the before.

Remember: choose a port that is not being used for the implementation of server socket and make sure that the firewall or any antivirus is not blocking the chosen port. For this article we define as 12345.

In Listing 1 we have the statement of the packages used in class. Note that we use "streams", "collections" and classs to construct forms.

Listing 1. Declaration of imports

  import java.util.ArrayList;
  import javax.swing.JLabel;
  import javax.swing.JOptionPane;
  import javax.swing.JTextField;

Next is the statement of class. See it extends Thread, so it's a kind of thread, adopting all the behaviors and properties of this class.

public class Server extends Thread {

In Listing 2 we have the statement of the static attributes and instances of class. The attribute "clients" is used to store the BufferedWriter each connected client and the server socket is used for the creation of server, which should theoretically be done only once.

Listing 2. Static Attributes

private static ArrayList<BufferedWriter> clients;           
  private static ServerSocket server; 
  private String nome;
  private Socket con;
  private InputStream in;  
  private InputStreamReader inr;  
  private BufferedReader bfr;

In Listing 3, we have the statement of the constructor method, which receives a socket object as a parameter and creates a BufferedReader object type, which points to the stream socket client.

Listing 3. Statement by the constructor

public Server(Socket con){
   this.con = con;
   try {
         in  = con.getInputStream();
         inr = new InputStreamReader(in);
          bfr = new BufferedReader(inr);
   } catch (IOException e) {

Listing 4 shows the method declaration "run": every time a new customer arrives at the server, this method is triggered and allocated on a thread and is also checking if there is any new message. If any, this will be read and the event "sentToAll" is triggered to send the message to other users connected to the chat.

Listing 4. Declaration of the run method

  * Method run
public void run(){
    String msg;
    OutputStream ou =  this.con.getOutputStream();
    Writer ouw = new OutputStreamWriter(ou);
    BufferedWriter bfw = new BufferedWriter(ouw); 
    nome = msg = bfr.readLine();
    while(!"Logout".equalsIgnoreCase(msg) && msg != null)
       msg = bfr.readLine();
       sendToAll(bfw, msg);
   }catch (Exception e) {

In Listing 5 we have the method declaration "sendToAll". When a client sends a message, the server receives and sends this to all the other connected clients. Note that this requires scrolling through the list of customers and send a copy of the message to each.

Listing 5. Declaration of sendToAll method

public void sendToAll(BufferedWriter bwOutput, String msg) throws  IOException 
  BufferedWriter bwS;
  for(BufferedWriter bw :  clients){
   bwS = (BufferedWriter)bw;
   if(!(bwOutput == bwS)){
     bw.write(nome + " -> " + msg+"\r\n");

Listing 6 shows the declaration of the main method, that when starting the server, make the socket server configuration and its port. See it starts creating a window to enter the door, then enters the "while (true)". In the "server.accept()" the system is blocked until a socket client to connect, if he does it a new thread type server is created.

Remember that the server class is a type of thread and starts the instruction "t.start()". Then the control flow returns to the line "server.accept()" and waits for another client to connect.

Listing 6. Declaration of the main method

   * Method main
   * @param args
public static void main(String []args) {
    //Cria os objetos necessário para instânciar o server
    JLabel lblMessage = new JLabel("Server Port:");
    JTextField txtPort = new JTextField("12345");
    Object[] texts = {lblMessage, txtPort };  
    JOptionPane.showMessageDialog(null, texts);
    server = new ServerSocket(Integer.parseInt(txtPort.getText()));
     clients = new ArrayList<BufferedWriter>();
    JOptionPane.showMessageDialog(null,"Active Server at Port: "+         
       System.out.println("Waiting for connection...");
       Socket con = server.accept();
       System.out.println("Client connected...");
       Thread t = new Server(con);
  }catch (Exception e) {
 }// End of of method main                      
} //End of of class

Listing 7 shows the packages used in the statement class.

Listing 7. Declaration of Imports

import java.awt.Color;
  import java.awt.event.ActionEvent;
  import java.awt.event.ActionListener;
  import java.awt.event.KeyEvent;
  import java.awt.event.KeyListener;
  import javax.swing.*;

The following is the statement of class:

public class Customer extends JFrame implements ActionListener, KeyListener {

For the construction of the form were used in the javax.swing package objects. Listing 8 shows the declaration of the static attributes and instances of class.

Listing 8. Declaration of atributes

private static final long serialVersionUID = 1L;
private JTextArea text;
private JTextField txtMsg;
private JButton btnSend;
private JButton btnLogout;
private JLabel lblHistorico;
private JLabel lblMsg;
private JPanel pnlContent;
private Socket socket;
private OutputStream ou ;
private Writer ouw; 
private BufferedWriter bfw;
private JTextField txtIP;
private JTextField txtPort;
private JTextField txtName;

When you run the client class a screen appears for the user enters some parameters such as the server IP, port, and the name that will be displayed to other users in the chat. The code is set to default IP, port 12345 and customer name.

Also note that the class inherits from JFrame, enabling the creation of forms and implementation of ActionListener and KeyListener interfaces to provide action buttons and action buttons, respectively.

Listing 9 shows the declaration of the constructor method, which checks the objects being instantiated for the construction of the chat screen. Remember that each client should be an independent body.

Listing 9. Declaration of the constructor method

public Client() throws IOException{                  
    JLabel lblMessage = new JLabel("Check!");
    txtIP = new JTextField("");
    txtPort = new JTextField("12345");
    txtName = new JTextField("Client");                
    Object[] texts = {lblMessage, txtIP, txtPort, txtName };  
    JOptionPane.showMessageDialog(null, texts);              
     pnlContent = new JPanel();
     text              = new JTextArea(10,20);
     text.setBackground(new Color(240,240,240));
     txtMsg                       = new JTextField(20);
     lblHistorico     = new JLabel("History");
     lblMsg        = new JLabel("Message");
     btnSend                     = new JButton("Send");
     btnSend.setToolTipText("Send Message");
     btnLogout           = new JButton("Logout");
     btnLogout.setToolTipText("Logout of Chat");
     JScrollPane scroll = new JScrollPane(text);
     text.setBorder(BorderFactory.createEtchedBorder(Color.BLUE,Colo  r.BLUE));
     txtMsg.setBorder(BorderFactory.createEtchedBorder(Color.BLUE, Color.BLUE));                    

The method of Listing 10 is used to connect the client to the server socket. In this method you can view the creation of the client socket and streams of communication.

Listing 10. Method Statement connect

public void connect() throws IOException{
  socket = new Socket(txtIP.getText(),Integer.parseInt(txtPort.getText()));
  ou = socket.getOutputStream();
  ouw = new OutputStreamWriter(ou);
  bfw = new BufferedWriter(ouw);

Listing 11 is the method used to send messages from the client to the server socket. So every time he write a message and press the "Enter" button, it will be sent to the server.

Listing 11. Statement of the method send message

  public void sendMessage(String msg) throws IOException{
      bfw.write("Desconnected \r\n");
      text.append("Desconnected \r\n");
      text.append( txtName.getText() + " diz -> " +         txtMsg.getText()+"\r\n");

In Listing 12 we have the method used to listen (receive) messages from the server. Every time someone send one, the method will be processed by the server and sends it to all connected clients, so the need to code.

Listing 12. Declaration method listen

public void listen() throws IOException{
   InputStream in = socket.getInputStream();
   InputStreamReader inr = new InputStreamReader(in);
   BufferedReader bfr = new BufferedReader(inr);
   String msg = "";
         msg = bfr.readLine();
         text.append("Server out! \r\n");

The method of Listing 13 is used to disconnect from the server socket. In it the system only closes the streams of communication.

Listing 13. Statement of the method out

   * Method usado quando o usuário clica em sair
   * @throws IOException retorna IO Exception caso dê algum erro.
   public void sair() throws IOException{

The method used to receive the actions of the user buttons is seen in Listing 14. It was like a switch: if the user presses the button "send" will then be sent a message, but will end the chat.

Listing 14. Statement of the actionPerformed method

public void actionPerformed(ActionEvent e) {
  try {
     } catch (IOException e1) {
          // TODO Auto-generated catch block

The method of Listing 15 is triggered when the user presses "Enter," verifying that the key code is Enter. If so, the message is sent to the server.

Listing 15. Statement of keyPressed method

public void keyPressed(KeyEvent e) {
    if(e.getKeyCode() == KeyEvent.VK_ENTER){
       try {
       } catch (IOException e1) {
           // TODO Auto-generated catch block
public void keyReleased(KeyEvent arg0) {
  // TODO Auto-generated method stub               
public void keyTyped(KeyEvent arg0) {
  // TODO Auto-generated method stub               

Listing 16 shows the main method, which is created only a client and are configured methods connect and listen.

Listing 16. Statement of the main method

public static void main(String []args) throws IOException{
   Client app = new Client();

After the implemented code in the Eclipse IDE or Netbeans, we have two classs: the and Run once class and class as often as deemed necessary, however, if you run only once, you will not see your message being sent to anyone.

We saw how simple the basic construction of a chat, since the idea of Thread and Socket is well understood.

I hope you enjoyed!

Julio is a System analyst and enthusiast of Information Technology. He is currently a developer at iFactory Solutions company, working in the development of strategic systems, is also a JAVA instructor. He has knowledge and experi...

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login