Loading...

How to make a java chat application using socket on both side?

How to make a java chat application using socket on both side?

When it comes to programming Java always remains at the top of developing complex applications because of the ecosystem Java has. Java provides many features to make complex things easy. In this article, we are going to make a java chat application that will work on multiple client sockets and create a working chat program in java.

This article assumes that you already know the fundamental of java and has a basic understanding of socket which covers socket programming and a little bit of knowledge about the client-server model.

If you are new to Java so check out the codedamn course for Java that covers all the fundamentals and takes you from beginner to master in Java programming you should take this before starting the chat program in java.

Introducing threads in socket programming

Socket programming is used to work with sockets which helps in making a network connection to the server. It works as a client-server method where the client sends the request to the server and the server responds to the client with the requested data.

While threads allow a program to perform multiple tasks simultaneously, rather than executing them one by one. It separates the execution flow and this separation gets executed simultaneously with other threads that are present in the same program.

Thread can be used to allow multiple tasks to be performed simultaneously in a single program. This makes it easy to work and perform complex and multiple operations along with the socket. Using a thread can be very useful while sending and receiving data on a socket, or performing other operations while it’s waiting for data.

To implement threads in socket programming in java we can use the Thread class and then override the run method. And after this, you can implement a socket with a socket class, which takes two inputs in the form of an IP address and port number.

What is java chat applications?

Java chat

Java chat applications are developed using the java programming language. Chat applications allow users to communicate with each other that should be in real-time. Where the messages are getting exchanged in real-time. It can run multiple client-server chats easily. Chat applications can be used for various purposes such as connecting with friends and using the application for business inquiries.

To develop a chat application in java there are various methods or ways that one can develop the application. The most simple way is to use Java Socket Class and Thread Class to create client-server architecture, where the server represents the back end of the chat application and the client represents the front end of the chat application.

This chat application will consist of three files Server.java represents the backend of the chat application and act as a provider, next is ClientHandler.java which implements thread and each message gets concurrently executed with the help of thread and it handles all the thread functionalities. The last Client.java represents the front-end part and how the client will work.

What is server-side programming?

Server-side Programming

Server-side programming is a way to develop an application that should run on a server and should be accessible by the client over any network. These programs are usually responsible for handling requests from clients, performing server tasks like data fetching, and handling the request of a client.

In java, server-side programming is typically implemented using java socket or using java servlets. These technologies handle and maintain the HTTP request from the client and generate dynamic content. To develop or make one server-side program in java you first need to install and set up the java environment which includes Java Development Kit (JDK) and one IDE such as Eclipse or IntelliJ.

But for this java chat application, you don’t need to have Eclipse or even VScode. You can simply run all the code in the codedamn playground i.e online IDE for Java programming which doesn’t require you to download or set up any sort of stuff. Just choose java and create a file and run the program.

Server Side Programming(Server.java)

Server Side java programming that listens for incoming connections on a specific port and sends a message back to the client when a connection is maintained. This uses a socket to communicate through the client’s IP address and access port number.

We are going to make a Server.java file that handles all the methods and is constructed to make a functional server side. It works like sending and receiving messages and forwarding them to the right place. There is an input-output stream that is used to read and write messages over the network. It might handle multiple clients concurrently using threads, or it might process requests using other java technologies.

// create a Server.java file and paste the code import java.io.IOException; // libraries import java.net.ServerSocket; import java.net.Socket; public class Server { // create serverSocket class private ServerSocket serverSocket; // constructor of ServerSocket class public Server(ServerSocket serverSocket){ this.serverSocket = serverSocket; } public void serverStart(){ try{ // check and loop the serverSocket while(!serverSocket.isClosed()){ Socket socket = serverSocket.accept(); System.out.println("New Friend Connected"); // implemented an object which handle runnable class ClientHandler clientHandler = new ClientHandler(socket); Thread thread = new Thread(clientHandler); thread.start(); } } catch (IOException e){ } } // this will close the server public void closerServer(){ try{ if(serverSocket != null){ serverSocket.close(); } } catch(IOException e){ e.printStackTrace(); } } public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(1234); Server server = new Server(serverSocket); server.serverStart(); } }
Code language: Java (java)

Features of server side programming

Features of server-side programming are many like connecting multiple-client servers and communicating between them. It acts as a source of handler where the server provides all the resources and functionality the client requires.

To make it more understandable server-side programming helps you to maintain the general dynamic data efficiently and control user interaction by allowing them to access the required data. It enhances the security of the application and multiple users can connect at a single time.

Server class

The server class will be responsible for listening to clients who wish to connect and when they do it will spawn a new thread to handle them. This class has a ServerScoket an object which is going to be responsible for listening to incoming connections or clients and creating a socket object to communicate with them

Check the server is running and is not closed by creating a method of startServer() which accepts the new connection from the client and inform other that a new client has connected.

It also has a ClientHandler object ( which will be created later on) and basically each object of ClientHandler the class will be responsible for communicating with a client and not only this but this class will implement the interface runnable.

Closing the connection if no errors are found which is implemented using closeServer() the method. It checks the server socket connection and if it’s null it returns IOException otherwise it closes the server.

public class Server { // create serverSocket class private ServerSocket serverSocket; // constructor of ServerSocket class public Server(ServerSocket serverSocket){ this.serverSocket = serverSocket; } public void serverStart(){ try{ // check and loop the serverSocket while(!serverSocket.isClosed()){ Socket socket = serverSocket.accept(); System.out.println("New Friend Connected"); // implemented an object which handle runnable class ClientHandler clientHandler = new ClientHandler(socket); Thread thread = new Thread(clientHandler); thread.start(); } } catch (IOException e){ } } // this will close the server public void closerServer(){ try{ if(serverSocket != null){ serverSocket.close(); } } catch(IOException e){ e.printStackTrace(); } } public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(1234); Server server = new Server(serverSocket); server.serverStart(); } }
Code language: PHP (php)

ClientHandler class

This class implements the runnable interface and overrides the run method. The first thing this class has is a static ArrayList of every client handler object that we have instantiated.

The main purpose of this ArrayList is to keep track of all our clients so that whenever a client sends a message we can loop through our array list of clients and sends the message to each client. This is static because it needs to belong to the class not each object of the class.

BufferedReader and BufferedWriter is used to send and receive data specifically messages to our clients and these will be messages that have been sent from other clients. Then it is going to be broadcast with the help of the above ArrayList.

DataInputStream and DataOutputStream are used as objects and it creates a new thread object which calls the start() method.

// create a ClientHandler.java file and paste the code public class ClientHandler implements Runnable{ public static ArrayList<ClientHandler>clientHandlers = new ArrayList<>(); public Socket socket; private BufferedReader buffReader; private BufferedWriter buffWriter; private String name; public ClientHandler(Socket socket){ // Constructors of all the private classes try{ this.socket = socket; this.buffWriter = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())); this.buffReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); this.name = buffReader.readLine(); clientHandlers.add(this); boradcastMessage("SERVER" + name + " has entered in the room"); } catch(IOException e){ closeAll(socket, buffReader, buffWriter); } } // run method override @Override public void run() { String messageFromClient; while(socket.isConnected()){ try{ messageFromClient = buffReader.readLine(); boradcastMessage(messageFromClient); } catch(IOException e){ closeAll(socket, buffReader, buffWriter); break; } } } public void boradcastMessage(String messageToSend){ for(ClientHandler clientHandler: clientHandlers){ try{ if(!clientHandler.name.equals(name)){ clientHandler.buffWriter.write(messageToSend); clientHandler.buffWriter.newLine(); clientHandler.buffWriter.flush(); } } catch(IOException e){ closeAll(socket,buffReader, buffWriter); } } } // notify if the user left the chat public void removeClientHandler(){ clientHandlers.remove(this); boradcastMessage("server " + name + " has gone"); } public void closeAll(Socket socket, BufferedReader buffReader, BufferedWriter buffWriter){ // handle the removeClient funciton removeClientHandler(); try{ if(buffReader!= null){ buffReader.close(); } if(buffWriter != null){ buffWriter.close(); } if(socket != null){ socket.close(); } } catch (IOException e){ e.getStackTrace(); } } }
Code language: Java (java)

The client handler handles the client entry and exit position and broadcasts the message to other clients that a particular user had left the chat and also informs the other clients that a particular user joined the chat.

It has a separate thread waiting for messages and another one working with the rest of the application because this makes the server responsive to certain activities.

What is client side programming?

Client-side programming is used in the development of applications that should run on the client side. This means that client-side programs are executed on a local host rather than on a remote network. It is often used to create dynamic and interactive client user interfaces. which should perform some operations and handle the complex equation on the server side.

Client-side programming only concerns with client and its need should be fulfilled. In Java, client-side programming is used with server-side programming, where the server handles complex operations and the client just displays the data in an interactive mode.

public class Client { // private classes for the clien private Socket socket; private BufferedReader buffReader; private BufferedWriter buffWriter; private String name; public Client(Socket socket, String name){ try{ // Constructors of all the private classes this.socket = socket; this.buffWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); this.buffReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); this.name = name; }catch (IOException e){ closeAll(socket, buffReader, buffWriter); } } // method to send messages using thread public void sendMessage(){ try{ buffWriter.write(name); buffWriter.newLine(); buffWriter.flush(); Scanner sc = new Scanner(System.in); while(socket.isConnected()){ String messageToSend = sc.nextLine(); buffWriter.write(name + ": " + messageToSend); buffWriter.newLine(); buffWriter.flush(); } } catch(IOException e){ closeAll(socket, buffReader, buffWriter); } } // method to read messages using thread public void readMessage(){ new Thread( new Runnable() { @Override public void run() { String msfFromGroupChat; while(socket.isConnected()){ try{ msfFromGroupChat = buffReader.readLine(); System.out.println(msfFromGroupChat); } catch (IOException e){ closeAll(socket, buffReader, buffWriter); } } } }).start(); } // method to close everything in the socket public void closeAll(Socket socket, BufferedReader buffReader, BufferedWriter buffWriter){ try{ if(buffReader!= null){ buffReader.close(); } if(buffWriter != null){ buffWriter.close(); } if(socket != null){ socket.close(); } } catch (IOException e){ e.getStackTrace(); } } // main method public static void main(String[] args) throws UnknownHostException, IOException{ Scanner sc = new Scanner(System.in); System.out.println("Enter your name"); String name = sc.nextLine(); Socket socket = new Socket("localhost", 1234); Client client = new Client(socket, name); client.readMessage(); client.sendMessage(); } }
Code language: Java (java)

Features of client side programming

Client-side programming runs on the user’s computer or devices unlike running on a remote server. The device user is using should meet all the requirements and resources to execute the program.

Interactivity and faster performance are the key benefits of user clients and it let users complete the task faster as it runs on the local server so initializing the task is faster than server-side programming.

SendMessage

SendMessage() the method used to send messages to our client handler, basically the connection the server has spawned to handle a client. It takes various inputs parameter to inclose with try-and-catch statements So that ClientHandler can identify them.

If an IOException occurs while attempting to send the message, the code calls a method called closeEverything to close the Socket, BufferedReader, and BufferedWriter objects.

public void sendMessage(){ try{ buffWriter.write(name); buffWriter.newLine(); buffWriter.flush(); Scanner sc = new Scanner(System.in); while(socket.isConnected()){ String messageToSend = sc.nextLine(); buffWriter.write(name + ": " + messageToSend); buffWriter.newLine(); buffWriter.flush(); } } catch(IOException e){ closeAll(socket, buffReader, buffWriter); } }
Code language: Java (java)

ReadMessage

ReadMessage() the method used for listening out for the messages that have been broadcasted. This is where we used a new thread as we listened for messages it acts as a blocking operation so we don’t want to spend our whole time waiting for a message and not being able to send one.

It takes a new thread and passes the runnable object. It enters a loop that continues as long as the socket is connected. Inside the loop, the code attempts to read a message from the server using a BufferedReader object and stores it in a variable called msfFromGroupChat.

Then last is closeEverything the method which takes three arguments and it closes the object if no null value is found. If an IOException occurs it will return the stack trace of an object.

public void readMessage(){ new Thread( new Runnable() { @Override public void run() { String msfFromGroupChat; while(socket.isConnected()){ try{ msfFromGroupChat = buffReader.readLine(); System.out.println(msfFromGroupChat); } catch (IOException e){ closeAll(socket, buffReader, buffWriter); } } } }).start(); }
Code language: Java (java)

Pros and cons of both side 

Client-side programming ProsClient-side programming cons
It can execute the task faster. Because it runs locally without any server. It has limited access to server resources and data.
Easy to create and work as a dynamic user interfacePerformance and scalability depend on the resource.
Compatible with any device.Security risks, as cod is visible to other users.
Client-side programming
Server-side programming prosServer-side programming cons
It can work and manipulate resources and data.It is slow in performance because of network communication.
It is more secure and can hide the user’s data from theft or illegal activities.It requires a dedicated server and infrastructure as a server to run all the programs efficiently.
It can handle the complex task.It solely depends on network connectivity.
Server-side programming

How to run the above program?

To run the program you can use IDE like IntelliJ or Eclipse and a library like Vscode works fine too. But these all require you to download and set up their respective environment. But there is one that works on web browsers and has all the functionalities like IDE’s.

Codedamn Playground provides you with an interactive way to code and runs your code directly in the browser and because of this, it doesn’t consume high memory and storage. To run the above java chat application program click on this Playground where the code is already returned and you just follow the below steps to get your java chat application running.

Step 1: Open three terminals wherein the first terminal we are going to run the server and the remaining two are for clients

Terminal

Step 2: In the first terminal type this command to run the server application. This will run the java server file.

java Server
Code language: Java (java)
java server

Step 3: In the remaining two terminals types this command to run clients

java Client
Code language: Java (java)
java client

Step 4: Enter the username for both clients respectively.

client 1
client 2

Step 5: Start chatting and create a meaningful conversation

client 1
client 2

Suggested Improvements 

  • You can create a graphical user interface with java GUI which makes this java chat application a bit more interactive.
  • You can add the date and time when the user sends the message.
  • You can also add the list of users present with just a simple method for this purpose.

Conclusion

While creating a client-server chat program application in java, I get to learn a lot of new stuff about threads and how threads can be accurately used in messages. It can support multiple client-server that makes it a group chat application.

The conclusion is java offers a lot of complex solutions which can be used to make a pretty good project. Explore java and make this java chat application a little bit better.

Frequently Asked Questions to Resolve (FAQs)

How do you make a chat app using socket IO?

For making a chat application using just Socket IO, you just need to simple server socket and create a client that should talk to the server and the server should forward the message to the desired client.

How do you program a chat application in Java?

To program a chat application in java you need to have a basic understanding of socket and networking this includes the experience of building with java. After that, you can start building your chat application with java.

How do I create a simple chat app in java?

To create a simple chat application in java here are points that you should consider while building the application:

  • Choose a networking library to use for the java chat application. Like Java Socket.
  • Create a server-side class that will handle all the incoming client requests and messages.
  • Create a client-side class that will handle and connect to the server. Sending and receiving messages should properly work with the client side.

How do you create a socket in Java?

In Java, you can create a socket using the java.net.Socket class. It is used for networking communication between two devices over any network. The code example of how to create a socket in java:

import java.net.Socket; Socket socket = new Socket("www.codedamn.com", 75);
Code language: Java (java)

Can I make a chat bot using Java?

Yes, it is possible to make a chatbot application using just Java. Though there are a few different ways that you can approach creating this application. To know more check out this article

Sharing is caring

Did you like what Anas Khan wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far