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