79 lines
2.3 KiB
Java
79 lines
2.3 KiB
Java
package chat;
|
|
|
|
import java.io.IOException;
|
|
import java.net.ServerSocket;
|
|
import java.net.Socket;
|
|
import java.util.Collections;
|
|
import java.util.HashSet;
|
|
import java.util.Set;
|
|
import java.util.concurrent.ExecutorService;
|
|
import java.util.concurrent.Executors;
|
|
|
|
public class ChatServer {
|
|
|
|
private final int port;
|
|
private final Set<ClientHandler> connectedClients;
|
|
private final ExecutorService threadPool;
|
|
|
|
public ChatServer(int port) {
|
|
this.port = port;
|
|
this.connectedClients = Collections.synchronizedSet(new HashSet<>());
|
|
this.threadPool = Executors.newCachedThreadPool();
|
|
}
|
|
|
|
public void start() {
|
|
try (ServerSocket serverSocket = new ServerSocket(port)) {
|
|
System.out.println("Chat server started on port " + port);
|
|
|
|
while (true) {
|
|
Socket clientSocket = serverSocket.accept();
|
|
ClientHandler clientHandler = new ClientHandler(clientSocket, this);
|
|
connectedClients.add(clientHandler);
|
|
threadPool.execute(clientHandler);
|
|
}
|
|
} catch (IOException e) {
|
|
System.err.println("Server error: " + e.getMessage());
|
|
} finally {
|
|
threadPool.shutdown();
|
|
}
|
|
}
|
|
|
|
public void broadcast(String message, ClientHandler sender) {
|
|
|
|
synchronized (connectedClients) {
|
|
for (ClientHandler client : connectedClients) {
|
|
if (client != sender) {
|
|
client.sendMessage(message);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
public void broadcastSystemMessage(String message) {
|
|
|
|
synchronized (connectedClients) {
|
|
for (ClientHandler client : connectedClients) {
|
|
client.sendMessage(message);
|
|
}
|
|
}
|
|
}
|
|
|
|
public void removeClient(ClientHandler clientHandler) {
|
|
|
|
connectedClients.remove(clientHandler);
|
|
broadcastSystemMessage("[System] " + clientHandler.getUsername() + " left the chat.");
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
int port = 12345;
|
|
if (args.length > 0) {
|
|
try {
|
|
port = Integer.parseInt(args[0]);
|
|
} catch (NumberFormatException e) {
|
|
System.err.println("Invalid port. Using default: " + port);
|
|
}
|
|
}
|
|
new ChatServer(port).start();
|
|
}
|
|
}
|