Programming Assignment Unit 7
Online Chat Application
1. [Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/**
* ChatServer manages multiple client connections using sockets.
* It assigns a unique user ID to each connected client and
broadcasts
* messages from one client to all connected clients.
*/
public class ChatServer {
private static final int PORT = 5000;
// Thread-safe set to store all connected client handlers
private static final Set<ClientHandler> connectedClients =
[Link]();
// Atomic counter used to assign unique user IDs
private static final AtomicInteger userCounter = new
AtomicInteger(1);
public static void main(String[] args) {
[Link]("Chat Server is starting...");
[Link]("Server is listening on port " + PORT);
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
while (true) {
Socket clientSocket = [Link]();
String userId = "User" +
[Link]();
ClientHandler clientHandler = new
ClientHandler(clientSocket, userId);
[Link](clientHandler);
[Link](userId + " connected.");
broadcastMessage("SERVER: " + userId + " has joined
the chat.");
Thread clientThread = new Thread(clientHandler);
[Link]();
}
} catch (IOException e) {
[Link]("Server error: " + [Link]());
}
}
/**
* Sends a message to all connected clients.
*/
private static void broadcastMessage(String message) {
for (ClientHandler client : connectedClients) {
[Link](message);
}
}
/**
* Handles communication with one connected client.
*/
private static class ClientHandler implements Runnable {
private final Socket socket;
private final String userId;
private PrintWriter output;
public ClientHandler(Socket socket, String userId) {
[Link] = socket;
[Link] = userId;
}
@Override
public void run() {
try (
BufferedReader input = new BufferedReader(
new
InputStreamReader([Link]()))
) {
output = new PrintWriter([Link](),
true);
[Link]("Welcome to the Online Chat
Application!");
[Link]("Your assigned ID is: " + userId);
[Link]("Type your message and press
Enter.");
[Link]("Type /quit to leave the chat.");
String message;
while ((message = [Link]()) != null) {
if ([Link]("/quit")) {
break;
}
broadcastMessage(userId + ": " + message);
}
} catch (IOException e) {
[Link](userId + " connection error: " +
[Link]());
} finally {
[Link](this);
broadcastMessage("SERVER: " + userId + " has left
the chat.");
[Link](userId + " disconnected.");
try {
[Link]();
} catch (IOException e) {
[Link]("Error closing socket for " +
userId);
}
}
}
/**
* Sends a message to this specific client.
*/
public void sendMessage(String message) {
if (output != null) {
[Link](message);
}
}
}
}
2. [Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/**
* ChatClient connects to the ChatServer using sockets.
* It allows the user to send messages and receive broadcast
messages
* from other connected users.
*/
public class ChatClient {
private static final String SERVER_ADDRESS = "localhost";
private static final int SERVER_PORT = 5000;
public static void main(String[] args) {
[Link]("Connecting to chat server...");
try (
Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
BufferedReader serverInput = new BufferedReader(
new InputStreamReader([Link]()));
PrintWriter serverOutput = new
PrintWriter([Link](), true);
BufferedReader keyboardInput = new BufferedReader(
new InputStreamReader([Link]))
) {
[Link]("Connected to the server.");
[Link]("----------------------------------");
Thread receiverThread = new Thread(() -> {
try {
String serverMessage;
while ((serverMessage =
[Link]()) != null) {
[Link](serverMessage);
}
} catch (IOException e) {
[Link]("Connection to server was
closed.");
}
});
[Link]();
String userMessage;
while ((userMessage = [Link]()) != null)
{
[Link](userMessage);
if ([Link]("/quit")) {
[Link]("You left the chat.");
break;
}
}
} catch (IOException e) {
[Link]("Client error: " + [Link]());
}
}
}
README File
Online Chat Application
Description
This project is a simple online chat application developed in Java. It uses socket programming
to allow multiple clients to connect to a central server. Each connected client receives a
unique user ID, such as User1, User2, or User3. When one client sends a message, the server
receives it and broadcasts it to all connected clients.
The project contains two main Java classes:
[Link]
This class creates the server, listens for incoming client connections, assigns unique user IDs,
maintains a list of connected users, and broadcasts messages.
[Link]
This class connects to the server, allows the user to type messages through a text-based
interface, and receives messages from other connected users.
Technologies Used
Java
Socket programming
ServerSocket
Socket
BufferedReader
PrintWriter
Multithreading
ConcurrentHashMap
AtomicInteger
How to Compile the Program
Open the terminal or command prompt in the folder where the files are saved.
Compile both files using:
javac [Link] [Link]
How to Run the Program
First, run the server:
java ChatServer
Then open another terminal window and run the first client:
java ChatClient
To test multiple users, open another terminal window and run another client:
java ChatClient
You can open more client windows to simulate more users.
How to Use the Chat Application
After connecting to the server, each client receives a unique ID.
The user can type a message and press Enter.
The message is sent to the server.
The server broadcasts the message to all connected clients.
To leave the chat, the user types:
/quit
Implementation Details
The server uses ServerSocket to listen for incoming connections on port 5000. Each time a
new client connects, the server creates a new ClientHandler object and starts a new thread for
that client. This allows multiple clients to communicate at the same time without blocking one
another.
The connected users are stored in a thread-safe set created using
[Link](). This helps prevent errors when several users connect or
disconnect at the same time. Unique user IDs are assigned using AtomicInteger, which safely
increases the user number for each new client.
The client uses one thread to receive messages from the server while the main thread allows
the user to type and send messages. This makes it possible for the client to send and receive
messages at the same time.
Sample Output
References
Codex, A. C. (2023, April 18). Java file handling: Reading and writing text and binary files.
REINTECH. [Link]
Eck, D. J. (2022). Introduction to programming using Java version 9, JavaFX edition. Hobart
and William Smith Colleges. [Link]
Oracle. (n.d.). Class ServerSocket. Oracle Java Documentation.
[Link]
Oracle. (n.d.). Class Socket. Oracle Java Documentation.
[Link]
Oracle. (n.d.). Class BufferedReader. Oracle Java Documentation.
[Link]
Oracle. (n.d.). Class PrintWriter. Oracle Java Documentation.
[Link]
Pankaj. (2022, August 4). Java socket programming: Socket server, client example.
DigitalOcean. [Link]
server-client