Implement a simple chat system using Socket Programming (TCP Sockets).
a) your chat system includes two types of components
i) A chat room and
ii) The client
b) System contains maximum 3 clients, each can enter or leave the system at any time and one can design GUI as given in Figure.
c) Chat room is long lived 'server' component and there is no GUI at server side.
d) All messages are to be broadcasted to all clients connected to the chat room.
[ Please write the reason for writing that line at the end of each line in the form of comments ]
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
private int pt;
private Set<String> names = new HashSet<>();
private Set<UserThread> userThreads = new HashSet<>();
public ChatServer(int pt) {
this.pt = pt;
}
public void execute() {
try (ServerSocket serverSocket = new ServerSocket(pt)) {
System.out.println("listening on port " + pt);
while (true) {
Socket s = serverSocket.accept();
System.out.println("New user connected");
UserThread newUser = new UserThread(s, this);
userThreads.add(newUser);
newUser.start();
}
} catch (IOException ex) {
System.out.println("Error in the server: " + ex.getMessage());
ex.printStackTrace();
}
}
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Syntax: java ChatServer <port-number>");
System.exit(0);
}
int pt = Integer.parseInt(args[0]);
ChatServer server = new ChatServer(pt);
server.execute();
}
void broadcast(String message, UserThread excludeUser) {
for (UserThread aUser : userThreads) {
if (aUser != excludeUser) {
aUser.sendMessage(message);
}
}
}
void addUserName(String userName) {
names.add(userName);
}
void removeUser(String userName, UserThread aUser) {
boolean removed = names.remove(userName);
if (removed) {
userThreads.remove(aUser);
System.out.println("The user " + userName + " quitted");
}
}
Set<String> getUserNames() {
return this.names;
}
boolean hasUsers() {
return !this.names.isEmpty();
}
}
Comments
Leave a comment