Blog | How I create chat application in JavaFX using socket programming


How I create chat application in JavaFX using socket programming


Posted on Thursday, October 31, 2019


These are 2 main steps on how I build JavaFX Chat application using socket programming

  1. Server: a single server responsible for listening and accepting to multiple connection request at a particular port (number)
    • One main thread (GUI thread) to run or display the output (window) in the desktop
    • One extra thread to continuously listen and accept to multiple connection request and
    • A thread for each and every successful connection (each connection means client connection to the server) to get message from client and send them back
  2. Client: one or multiple clients which request for connection by providing host (ip address) and port number
    • One main thread to run or display the output (window) in the desktop
    • One extra thread to continuously receive the incoming message from the server

Output: 

javafx_socketprogramming_chatapplication

 

Download: JavaFXSocketProgramming .

It is better to download it now and check the file line by line while i will explain the code in the following paragraph.

Explanation

  1. Server: ServerJavaFX.java represents a server. Run this file only once.
    • One main thread (GUI thread) to display the window: It uses Text Area and Scroll Pane.
    • One extra thread to continuously listen and accept to multiple connection request and
      • Code: starting line 52-56, 62-65, 77
    • A thread for each and every successful connection (each connection means client connection to the server). Each connection is represented by file TaskClientConnection.java which implements Runnable interface. This file is responsible for receiving message from client and sending message back to client. In ServerJavaFx.java, after successful connection of clients, they are stored in a List<> variable so that later on it can send message to all connected cilents through broadcast() method (line 88-93) in the same class.
      • Code: ServerJavaFX.java: line 64 to 69
    • //ServerJavaFx.java starting from line 52-77
              //create a new thread
              new Thread(() -> {
                  try {
                      // Create a server socket
                      ServerSocket serverSocket = new ServerSocket(ConnectionUtil.port);
                      
                      //append message of the Text Area of UI (GUI Thread)
                      Platform.runLater(()
                              -> txtAreaDisplay.appendText("New server started at " + new Date() + '\n'));
      
                      //continous loop
                      while (true) {
                          // Listen for a connection request, add new connection to the list
                          Socket socket = serverSocket.accept();
                          TaskClientConnection connection = new TaskClientConnection(socket, this);
                          connectionList.add(connection);
      
                          //create a new thread
                          Thread thread = new Thread(connection);
                          thread.start();
      
                      }
                  } catch (IOException ex) {
                        txtAreaDisplay.appendText(ex.toString() + '\n');
                  }
              }).start();
      
        //line starting at 88-93
        //send message to all connected clients
          public void broadcast(String message) {
              for (TaskClientConnection clientConnection : this.connectionList) {
                  clientConnection.sendMessage(message);
              }
          }
      
      
    • Following is the piece of code inside the run() method of TaskClientConnection.java: line 41 to 46
    • //TaskClientConnection.java, starting line 41-46
      while (true) {
                      // Get message from the client
                      String message = input.readUTF();
      
                      //send message via server broadcast
                      server.broadcast(message);
                      //server broadcast method send message to all connected clients.
                      //clients are stored in List<> variable. 
      
      
  2. Client: ClientJavaFX.java represents client. You can run this file multiple times which means multiple windows i.e. multiple clients
    • One main thread (GUI thread) to display the window: It uses Text Area, Text Field, Button, HBox, VBox and Scroll Pane. When it starts, it request for connection to the server using host and port (code line: 87). This thread is further responsible for sending message to server. It is achieved through providing a click event handler on Button. It will send the message unless the message is empty.
    • //ClientJavaFx.java, starting line at 85-102
       try {
                  // Create a socket to connect to the server
                  Socket socket = new Socket(ConnectionUtil.host, ConnectionUtil.port);
      
                  //Connection successful
                  txtAreaDisplay.appendText("Connected. \n");
                
                  // Create an output stream to send data to the server
                  output = new DataOutputStream(socket.getOutputStream());
      
                  //create a thread in order to read message from server continuously
                  TaskReadThread task = new TaskReadThread(socket, this);
                  Thread thread = new Thread(task);
                  thread.start();
              } catch (IOException ex) {
                  
                  txtAreaDisplay.appendText(ex.toString() + '\n');
              }
      
      
      
      
      //starting line at 115-135
       private class ButtonListener implements EventHandler<ActionEvent> {
      
              @Override
              public void handle(ActionEvent e) {
                  try {
                      //get username and message
                      String username = txtName.getText().trim();
                      String message = txtInput.getText().trim();
      
                      //if username is empty set it to 'Unknown' 
                      if (username.length() == 0) {
                          username = "Unknown";
                      }
                      //if message is empty, just return : don't send the message
                      if (message.length() == 0) {
                          return;
                      }
      
                      //send message to server
                      output.writeUTF("[" + username + "]: " + message + "");
                      output.flush();              
      
      
    • One extra thread to continuously receive the incoming message from the server. It is represented by the TaskReadThread.java file which implements Runnable interface. It basically reads message from the server and displays in GUI.
    • //TaskReadThread.java, starting line at 31-46
      @Override 
          public void run() {
              //continuously loop it
              while (true) {
                  try {
                      //Create data input stream
                      input = new DataInputStream(socket.getInputStream());
      
                      //get input from the client
                      String message = input.readUTF();
      
                      //append message of the Text Area of UI (GUI Thread)
                      Platform.runLater(() -> {
                          //display the message in the textarea
                          client.txtAreaDisplay.appendText(message + "\n");
                      });
      
      

5 classes explanation:

  • Server
    • (1) ServerJavaFX.java : it represents server. Run it only once
    • (2) TaskClientConnection.java: it is part of the client which represents each and every successful client connection and is responsible for sending to and receiving message from client
  • Client
    • (3) ClientJavaFX.java: it represents client. It can be run multiple times.
    • (4) TaskReadThread.java: it is part of client which is responsible for receiving message from the server
  • (5) ConnectionUtil.java: contains static variables that holds host (ip address) and port (number)

The chat application was part of our assignments in our university; Charles Sturt University, Sydney. I am just sharing my learning here so that it could be helpful to you.

Following site (console application) was the most helpful resource where I research through and got understanding and build chat application in JavaFX: codejava.net resource