Assignment Unit 7
Assignment Unit 7
Assignment Unit 7
This assignment aims to assess your skills in socket programming, client-server communication,
Assignment Instructions
You are tasked with developing a simple online chat application using Java. The application
should allow multiple users to connect to a central server, send messages, and receive messages
Requirements:
Server Implementation:
a. Create a server class, ChatServer, using socket programming to manage connections from
multiple clients.
b. The server should be able to handle incoming connections, assign a unique user ID to each
import java.io.*;
import java.net.*;
import java.util.*;
System.out.println("Server is running...");
while (true) {
new ClientHandler(serverSocket.accept()).start();
} catch (IOException e) {
e.printStackTrace();
this.socket = socket;
this.userId = userIdCounter++;
try {
InputStreamReader(socket.getInputStream()));
clientWriters.add(writer);
String message;
broadcast(message);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
clientWriters.remove(writer);
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
Client Implementation:
a. Implement a client class, ChatClient, that connects to the server using sockets.
b. Each client should be able to send messages to the server, which will broadcast the messages
import java.io.*;
import java.net.*;
import java.util.Scanner;
InputStreamReader(socket.getInputStream()));
try {
String message;
System.out.println(message);
} catch (IOException e) {
e.printStackTrace();
});
receiveThread.start();
String userInput;
serverWriter.println(userInput);
} catch (IOException e) {
e.printStackTrace();
}
Sample Output:
Server console:
Server is running...
User 1 connected.
User 2 connected.
User 1 disconnected.
Client console:
Hello everyone!
User 2: Hi there!