init project
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
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) {
|
||||
// step 1: iterate through connectedClients safely
|
||||
// step 2: skip the sender client
|
||||
// step 3: send message to remaining clients using sendMessage
|
||||
}
|
||||
|
||||
public void broadcastSystemMessage(String message) {
|
||||
// step 1: iterate through all connected clients
|
||||
// step 2: send system message to each client
|
||||
}
|
||||
|
||||
public void removeClient(ClientHandler clientHandler) {
|
||||
// step 1: remove client from connectedClients set
|
||||
// step 2: retrieve username from clientHandler
|
||||
// step 3: broadcast system message about user leaving
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user