Assignment Title - Online Chat Application
Assignment Title - Online Chat Application
UNIT 7
Assignment Title: Online Chat Application
Computer Science Department: University of the People
CS 1103-01 - AY2025-T1 - Programming 2
Khushboo Sharma
OCTOBER 23, 2024
2
Assignment Title: Online Chat Application
This is a simple chat application with both server and client components. This application
allows multiple users to connect to a central server, send messages, and receive messages
from other users.
Key features implemented:
1. Server (ChatServer.java):
o Handles multiple clients using threads
o Maintains a set of connected clients using ConcurrentHashMap for thread
safety
o Assigns unique user IDs to each client
o Broadcasts messages to all other connected clients
o Handles client disconnections gracefully
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* Main server class that handles multiple client connections and message distribution
*/
public class ChatServer {
// Server configuration constants
private static final int PORT = 9001;
/**
* Starts the server and listens for incoming client connections
*/
public void start() {
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("Chat Server started on port " + PORT);
/**
* Broadcasts a message to all connected clients except the sender
* @param message Message to broadcast
* @param sender Client who sent the message
*/
private void broadcast(String message, ClientHandler sender) {
// Add timestamp to the message
String timestamp = LocalDateTime.now().format(timeFormatter);
String formattedMessage = String.format("[%s] %s", timestamp, message);
/**
* Sends a private message from one user to another
* @param senderNickname Nickname of the sender
* @param receiverNickname Nickname of the receiver
* @param message Message content
*/
private void sendPrivateMessage(String senderNickname, String receiverNickname, String
message) {
ClientHandler receiver = clients.get(receiverNickname);
String timestamp = LocalDateTime.now().format(timeFormatter);
String formattedMessage = String.format("[%s] [PM from %s] %s", timestamp,
senderNickname, message);
if (receiver != null) {
receiver.sendMessage(formattedMessage);
} else {
// Notify sender if recipient doesn't exist
clients.get(senderNickname).sendMessage("User " + receiverNickname + " not found.");
}
}
4
Assignment Title: Online Chat Application
/**
* Inner class to handle individual client connections
*/
private class ClientHandler implements Runnable {
private Socket socket;
private PrintWriter out;
private BufferedReader in;
private int userId;
private String nickname;
/**
* Constructor for ClientHandler
* @param socket Client's socket connection
* @param userId Unique ID assigned to the client
*/
public ClientHandler(Socket socket, int userId) {
this.socket = socket;
this.userId = userId;
try {
// Initialize input and output streams
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Sends a message to this client
* @param message Message to send
*/
public void sendMessage(String message) {
out.println(message);
}
/**
* Handles various chat commands
* @param command Command string from client
*/
private void handleCommand(String command) {
String[] parts = command.split("\\s+", 3);
String cmd = parts[0].toLowerCase();
switch (cmd) {
case "/nick":
// Handle nickname setting
if (parts.length < 2) {
sendMessage("Usage: /nick <nickname>");
return;
}
String newNick = parts[1];
if (clients.containsKey(newNick)) {
5
Assignment Title: Online Chat Application
sendMessage("Nickname already in use.");
return;
}
// Remove old nickname and add new one
if (nickname != null) {
clients.remove(nickname);
}
nickname = newNick;
clients.put(nickname, this);
broadcast(nickname + " joined the chat!", this);
break;
case "/list":
// Show list of connected users
sendMessage("Connected users: " + String.join(", ", clients.keySet()));
break;
case "/pm":
// Handle private messaging
if (parts.length < 3) {
sendMessage("Usage: /pm <nickname> <message>");
return;
}
String receiver = parts[1];
String message = parts[2];
sendPrivateMessage(nickname, receiver, message);
break;
case "/help":
// Display available commands
sendMessage("Available commands:\n" +
"/nick <nickname> - Set your nickname\n" +
"/list - List all connected users\n" +
"/pm <nickname> <message> - Send private message\n" +
"/help - Show this help message");
break;
default:
sendMessage("Unknown command. Type /help for available commands.");
}
}
/**
* Main run method for handling client communication
*/
@Override
public void run() {
try {
// Initial welcome messages
sendMessage("Welcome! Please set your nickname using /nick <nickname>");
sendMessage("Type /help for available commands");
6
Assignment Title: Online Chat Application
String message;
// Main message processing loop
while ((message = in.readLine()) != null) {
if (message.startsWith("/")) {
// Handle commands
handleCommand(message);
} else {
// Handle regular messages
if (nickname == null) {
sendMessage("Please set your nickname first using /nick <nickname>");
continue;
}
broadcast(nickname + ": " + message, this);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// Cleanup when client disconnects
try {
if (nickname != null) {
clients.remove(nickname);
broadcast(nickname + " left the chat!", this);
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2. Client (ChatClient.java):
/**
* Client class that handles connection to the server and user interface
*/
public class ChatClient {
// Connection constants
private static final String SERVER_ADDRESS = "localhost";
private static final int SERVER_PORT = 9001;
// Connection-related objects
private Socket socket;
private PrintWriter out;
private BufferedReader in;
private BufferedReader userInput;
/**
* Starts the client and handles user input
*/
public void start() {
try {
// Initialize connection and streams
socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
userInput = new BufferedReader(new InputStreamReader(System.in));
/**
* Handles receiving and displaying messages from the server
*/
private void receiveMessages() {
try {
String message;
while ((message = in.readLine()) != null) {
// Apply different colors based on message type
if (message.contains("[PM from")) {
// Private messages in green
System.out.println(ANSI_GREEN + message + ANSI_RESET);
} else if (message.startsWith("Available commands:") ||
message.startsWith("Usage:") ||
message.startsWith("Connected users:")) {
// System messages in blue
System.out.println(ANSI_BLUE + message + ANSI_RESET);
} else {
// Regular messages in default color
System.out.println(message);
}
}
} catch (IOException e) {
System.out.println("Disconnected from server.");
}
}
/**
* Cleans up resources when client exits
*/
private void cleanup() {
try {
if (socket != null) socket.close();
if (in != null) in.close();
if (out != null) out.close();
if (userInput != null) userInput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
APPLICATION OUTPUT:
10
Assignment Title: Online Chat Application