0% found this document useful (0 votes)
17 views10 pages

Assignment Title - Online Chat Application

Uploaded by

eddburkes
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)
17 views10 pages

Assignment Title - Online Chat Application

Uploaded by

eddburkes
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
You are on page 1/ 10

1

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;

// Data structures to store client information


// Using ConcurrentHashMap for thread-safe operations
private Map<String, ClientHandler> clients = new ConcurrentHashMap<>();

// Atomic counter for generating unique user IDs


private AtomicInteger userIdCounter = new AtomicInteger(1);

// Formatter for timestamp generation


private static final DateTimeFormatter timeFormatter =
DateTimeFormatter.ofPattern("HH:mm:ss");

/**
* 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);

// Infinite loop to accept new client connections


while (true) {
3
Assignment Title: Online Chat Application
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected: " + clientSocket);

// Create and start a new handler thread for each client


ClientHandler clientHandler = new ClientHandler(clientSocket,
userIdCounter.getAndIncrement());
new Thread(clientHandler).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 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);

// Send message to all clients except the sender


for (ClientHandler client : clients.values()) {
if (client != sender) {
client.sendMessage(formattedMessage);
}
}
}

/**
* 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();
}
}
}
}

public static void main(String[] args) {


new ChatServer().start();
}
}
7
Assignment Title: Online Chat Application

2. Client (ChatClient.java):

 Connects to the server using sockets


 Uses separate threads for sending and receiving messages
 Provides a simple console-based interface
 Handles disconnections properly with cleanup

/**
* 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;

// ANSI color codes for message formatting


private static final String ANSI_RESET = "\u001B[0m";
private static final String ANSI_GREEN = "\u001B[32m";
private static final String ANSI_BLUE = "\u001B[34m";

// 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));

// Start thread for receiving messages


new Thread(this::receiveMessages).start();

// Main thread handles user input


String message;
while ((message = userInput.readLine()) != null) {
out.println(message);
}
} catch (IOException e) {
e.printStackTrace();
8
Assignment Title: Online Chat Application
} finally {
cleanup();
}
}

/**
* 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();
}
}

public static void main(String[] args) {


new ChatClient().start();
}
}
9
Assignment Title: Online Chat Application

APPLICATION OUTPUT:
10
Assignment Title: Online Chat Application

You might also like