0% found this document useful (0 votes)
39 views6 pages

Java Multi-User Chat Application

The document describes a multi-user online chat application developed in Java using socket programming, featuring a central server (ChatServer) that manages client connections and broadcasts messages. Each client (ChatClient) connects to the server, receives a unique user ID, and can send and receive messages in real-time through a text-based interface. The application illustrates key concepts of client-server communication and multithreading, serving as a practical example of socket programming principles.

Uploaded by

falakfraidoon
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views6 pages

Java Multi-User Chat Application

The document describes a multi-user online chat application developed in Java using socket programming, featuring a central server (ChatServer) that manages client connections and broadcasts messages. Each client (ChatClient) connects to the server, receives a unique user ID, and can send and receive messages in real-time through a text-based interface. The application illustrates key concepts of client-server communication and multithreading, serving as a practical example of socket programming principles.

Uploaded by

falakfraidoon
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java assignment unite 7

The online chat application developed using Java utilizes socket programming to facilitate real-
time communication between multiple users. The architecture consists of a central server,
ChatServer, which manages connections from various clients, assigns unique user IDs, and
broadcasts messages to all connected users. Each client, represented by the ChatClient class,
connects to the server and can send and receive messages in a text-based interface. The server
listens for incoming connections and spawns a new thread for each client, ensuring that messages
from one user are transmitted to all other connected users seamlessly. The user interface allows
clients to input messages easily and receive real-time updates, creating an interactive chat
experience. The application demonstrates fundamental concepts of client-server communication,
including user management and multithreading, providing a solid foundation for understanding
networked applications in Java. Overall, this chat application serves as a practical
implementation of socket programming principles, allowing users to engage in dynamic
conversations within a simple yet effective framework.

Source code:
Chatserver:
import [Link].*;
import [Link].*;
import [Link].*;

public class ChatServer {


private static final int PORT = 12345;
private static Set<PrintWriter> clientWriters = new HashSet<>();

public static void main(String[] args) {


[Link]("Chat server started...");
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
while (true) {
new ClientHandler([Link]()).start();
}
} catch (IOException e) {
[Link]();
}
}

private static class ClientHandler extends Thread {


private Socket socket;
private PrintWriter out;
private BufferedReader in;
private String userId;
public ClientHandler(Socket socket) {
[Link] = socket;
}

public void run() {


try {
in = new BufferedReader(new
InputStreamReader([Link]()));
out = new PrintWriter([Link](), true);
synchronized (clientWriters) {
[Link](out);
}

userId = "User" + [Link](); // Assign unique


user ID
[Link]("Welcome " + userId + "! You are now
connected to the chat.");

String message;
while ((message = [Link]()) != null) {
[Link](userId + ": " + message); //
Server-side message display
broadcast(userId + ": " + message);
}
} catch (IOException e) {
[Link]();
} finally {
try {
[Link]();
} catch (IOException e) {
[Link]();
}
synchronized (clientWriters) {
[Link](out);
}
[Link](userId + " has disconnected.");
}
}

private void broadcast(String message) {


synchronized (clientWriters) {
for (PrintWriter writer : clientWriters) {
[Link](message);
}
}
}
}
}

ChatClient :
import [Link].*;
import [Link].*;
import [Link];

public class ChatClient {


private static final String SERVER_ADDRESS = "localhost"; // Change
this to the server's IP if needed
private static final int SERVER_PORT = 12345;

public static void main(String[] args) throws IOException {


// Establish connection to the server
Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](),
true);
Scanner scanner = new Scanner([Link]);

// Thread to receive messages from the server


Thread messageReceiver = new Thread(() -> {
try {
String serverMessage;
while ((serverMessage = [Link]()) != null) {
[Link](serverMessage); // Display server
messages (prefixed with user IDs)
}
} catch (IOException e) {
[Link]("Disconnected from server.");
}
});

[Link]();

// Input for sending messages


while (true) {
[Link]("Enter message: ");
String message = [Link](); // Scanner reads input
from the console
if ([Link]("/quit")) {
[Link]("Exiting chat...");
break; // Break out of loop if the user types '/quit'
}
[Link](message); // Sends the input to the server
}

// Cleanup and close resources


try {
[Link](); // Close the connection
[Link]();
} catch (IOException e) {
[Link]();
}
}
}

Readme file:
# Online Chat Application

## Overview
This is a simple multi-user chat application using Java socket programming. Users can connect to a
central server, send messages, and receive messages from other users. Each user is assigned a unique user
ID (e.g., User 1, User 2) upon connecting to the server.

## How to Run

1. Compile the Java files:


javac [Link] [Link]

2. Start the server:


java ChatServer
3. Start each client instance (run in separate terminals or machines):
java ChatClient
4. Enter messages to chat with other users. To exit, type `/quit`.

## Features
- Server assigns a unique user ID to each connected client. Like User 1 , User 2 ………
- Messages are broadcast to all connected users.
- Simple text-based user interface for input and message display.

Screenshot of the output:


References:
Gaddis, T. (2019). Starting Out with Java: From Control Structures through Objects (6th ed.).
Pearson.
Eck, D. J. (2022). Introduction to programming using Java: Version 9, Swing
edition. Hobart and William Smith Colleges.

W3Schools. (n.d.). Java tutorial. W3Schools. [Link]

Sierra, K., & Bates, B. (2014). Head First Java (2nd ed.). O'Reilly Media.

Oracle. (n.d.). Java SE documentation. Retrieved from


[Link]

Common questions

Powered by AI

The chat application illustrates several key Java programming concepts including socket programming for network communications, multithreading for handling concurrent client connections, synchronization to manage shared resources safely across threads, and basic user interface handling for command-line input and output. These concepts provide a foundation for building more complex networked applications in Java .

The application achieves real-time updates through the use of multithreading and socket programming. Each client runs a separate messageReceiver thread that continuously listens for messages from the server. As a result, users receive updates instantaneously whenever new messages are broadcast. This setup provides an interactive and dynamic user experience, essential for effective communication in chat applications, as it allows for immediate feedback and conversation flow .

The scalability of the chat application is limited by its architecture. As each connection spawns a new thread, the server might face performance degradation if the number of users grows significantly, due to increased CPU and memory usage. The current design does not include load balancing or distributed server setups, which could further limit performance under heavy load. Optimizations such as using a non-blocking I/O model could improve scalability .

Potential improvements to the user interface include adding a graphical user interface (GUI) using Java Swing or JavaFX to replace the current text-based input and display. Enhancements could include features like message notification sounds, user presence indicators, emoticons support, and message history. Such improvements would make the interface more user-friendly and visually appealing, thus enhancing the overall chat experience .

The chat application, in its current form, lacks measures for encryption, authentication, and authorization. Without encryption, messages are susceptible to eavesdropping during transmission. The absence of authentication opens the possibility for unauthorized users to connect to the server and communicate. Similarly, without proper authorization, malicious users might exploit system resources or disrupt service for legitimate clients. Implementing these security features could significantly enhance the architecture's security .

The ClientHandler class is responsible for managing the communication between the server and a connected client. It reads input messages from the client, assigns a unique user ID upon connection, broadcasts received messages to all other clients, and handles disconnection scenarios. The class also manages the cleanup process when a client disconnects, ensuring that the associated PrintWriter is removed from the clientWriters set .

The ChatServer class manages multiple client connections by using multithreading. It listens for incoming connections on a specified port using a ServerSocket. For each incoming connection, it creates a new ClientHandler thread, which handles the communication with a specific client. This allows the server to handle multiple clients simultaneously, as each client communication is managed in a separate thread .

Synchronization is crucial for preventing concurrent modification issues in the chat application. The broadcast method in the ClientHandler class uses a synchronized block to ensure that access to the clientWriters set is thread-safe. This prevents issues such as concurrent addition or removal of clients while iterating over the set to send messages, ensuring that all connected users receive broadcasted messages consistently .

The chat application ensures unique identification by assigning each connected client a unique user ID in the form of 'User' followed by the current size of the clientWriters set. This is done in the run method of each ClientHandler instance. This approach helps differentiate messages from different users, making the chat session organized and enhancing clarity in user interactions .

The central server architecture simplifies user management by maintaining a single point of communication, which routes messages among users. This design centralizes control, allowing easy implementation of features such as logging, monitoring, and user management. It also reduces complexity on the client side, as each client only needs to connect to the server rather than managing multiple peer connections. However, it might introduce a single point of failure and scalability concerns .

You might also like