How to Implement a Simple Chat Application Using Sockets in Java?
Last Updated :
08 Jan, 2025
In this article, we will create a simple chat application using Java socket programming. Before we are going to discuss our topic, we must know Socket in Java. Java Socket connects two different JREs (Java Runtime Environment).
- Java sockets can be connection-oriented or connection-less.
- In Java, we have the java.net package.
- Java Socket can be connectionless or connection-oriented.
Java Client
On the Java client side, we will pass the two most important information to the Socket class. This information connects the Java Client Socket to the Java Server Socket.
- IP Address of Server and,
- Port Number
In the Java client, we create a new thread when each new message is received from the Java Server Client.
Java
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
private static final String SERVER_ADDRESS = "localhost";
private static final int SERVER_PORT = 12345;
public static void main(String[] args) {
try {
Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
System.out.println("Connected to the chat server!");
// Setting up input and output streams
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// Start a thread to handle incoming messages
new Thread(() -> {
try {
String serverResponse;
while ((serverResponse = in.readLine()) != null) {
System.out.println(serverResponse);
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
// Read messages from the console and send to the server
Scanner scanner = new Scanner(System.in);
String userInput;
while (true) {
userInput = scanner.nextLine();
out.println(userInput);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Java Server
In the server side. we will get the username of each connected client and stores each client in the CopyOnWriteArrayList after accepting the connection from the connected client. Every time create another thread for each client. Every message will be broadcast to every connected client.
Java
import java.io.*;
import java.net.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.Scanner;
public class Server {
private static final int PORT = 12346;
private static CopyOnWriteArrayList<ClientHandler> clients = new CopyOnWriteArrayList<>();
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Server is running and waiting for connections...");
// Thread to handle server admin input
new Thread(() -> {
Scanner scanner = new Scanner(System.in);
while (true) {
String serverMessage = scanner.nextLine();
broadcast("[Server]: " + serverMessage, null);
}
}).start();
// Accept incoming connections
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected: " + clientSocket);
// Create a new client handler for the connected client
ClientHandler clientHandler = new ClientHandler(clientSocket);
clients.add(clientHandler);
new Thread(clientHandler).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Broadcast a message to all clients
public static void broadcast(String message, ClientHandler sender) {
for (ClientHandler client : clients) {
if (client != sender) {
client.sendMessage(message);
}
}
}
// Internal class to handle client connections
private static class ClientHandler implements Runnable {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
private String username;
public ClientHandler(Socket socket) {
this.clientSocket = socket;
try {
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
// Get the username from the client
out.println("Enter your username:");
username = in.readLine();
System.out.println("User " + username + " connected.");
out.println("Welcome to the chat, " + username + "!");
out.println("Type Your Message");
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("[" + username + "]: " + inputLine);
broadcast("[" + username + "]: " + inputLine, this);
}
// Remove the client handler from the list
clients.remove(this);
System.out.println("User " + username + " disconnected.");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
out.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void sendMessage(String message) {
out.println(message);
}
}
}
Run the Application
First Run the Server.js file in the terminal or command Prompt for better visual. Using the following command,
javac Server.java
java Server.java
Now, run the Client.java file in another terminal or command Prompt for better visual. Using the following command,
javac Client.java
java Client.java
Output:
Below is the Output that demonstrates the Basic Socket Communication between a Server and Client.
Similar Reads
How to Implement Peer-to-Peer Communication in Java? Peer-to-peer communication is a decentralized form of communication where two or more devices communicate directly with each other without the need for a central server. In peer-to-peer communication, each peer can act as both a client and a server, enabling them to both send and receive data. Peer-
2 min read
How to Implement Basic Error Handling in Socket Programming in Java? Socket programming is nothing but, a fundamental aspect of network communication that enables the applications to communicate over the network using TCP/IP or UDP protocols. In Java, socket programming is allowed to the developers for creating applications of the client-server, where the data can be
4 min read
How to Implement a Distributed Caching System Using Java Networking? In Java, a distributed caching system is used to store frequently accessed data in the memory across multiple servers, improving the performance and scalability of the applications. We can implement the simple distributed caching system using Java networking, and it can implement multiple cache node
3 min read
How to Secure Communication Using SSL/TLS in Java? Secure Sockets Layer (SSL) or Transport Layer Security (TLS) are cryptographic protocols designed to provide secure communication over the computer network. These protocols are establish an encrypted connection between the client and the server, make sure that the data exchanged between them remains
5 min read
Simple Calculator using Java Socket Programming Prerequisite: Socket Programming in Java First, we understand the basics of java socket programming. Java Socket is used to communicate between two different JREs. Java socket can be connection-oriented or connection-less. In java, we have a package called "java.net". In this package, we have two cl
3 min read