ServerAppTest.java

mail@pastecode.io avatar
unknown
java
a year ago
2.4 kB
3
Indexable
Never
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.UUID;

public class ServerAppTest {
    private static HashMap<String, PrintWriter> clients = new HashMap<>();
    public void Connect(int port) {
        int portNumber = port;

        try (ServerSocket serverSocket = new ServerSocket(portNumber)) {
            System.out.println("Server listening on port " + portNumber);

            while (true) {
                Socket clientSocket = serverSocket.accept();
                String sessionId = UUID.randomUUID().toString();
                new ClientHandler(clientSocket, sessionId).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        
    }

    private static class ClientHandler extends Thread {
        private Socket clientSocket;
        private String sessionId;
        private PrintWriter writer;

        public ClientHandler(Socket socket, String sessionId) {
            this.clientSocket = socket;
            this.sessionId = sessionId;
        }

        @Override
        public void run() {
            try (
                BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))
            ) {
                String message;
                writer = new PrintWriter(clientSocket.getOutputStream(), true);

                writer.println("Please enter your username:");
                String username = reader.readLine();
                System.out.println("[" + sessionId + "] User connected: " + username);
                clients.put(username, writer);

                while ((message = reader.readLine()) != null) {
                    System.out.println("[" + sessionId + "] " + username + ": " + message);
                    broadcastMessage("[" + username + "] " + message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                clients.remove(sessionId);
                writer.close();
            }
        }
    }

    private static void broadcastMessage(String message) {
        for (PrintWriter clientWriter : clients.values()) {
            clientWriter.println(message);
        }
    }
}