Untitled

mail@pastecode.io avatar
unknown
java
2 months ago
5.1 kB
2
Indexable
Never
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;

public class ChatServer {
    private ServerSocket serverSocket;
    private List<ClientHandler> clients = new ArrayList<>();
    private FileWriter historyFileWriter;

    public ChatServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
        historyFileWriter = new FileWriter("chat_history.txt", true);
    }

    public void start() {
        System.out.println("Server started. Waiting for clients...");

        while (true) {
            try {
                Socket clientSocket = serverSocket.accept();
                System.out.println("New client connected: " + clientSocket);
                ClientHandler clientHandler = new ClientHandler(clientSocket);
                new Thread(clientHandler).start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void broadcastUsers() {
        StringBuilder userList = new StringBuilder("Users online: ");
        for (ClientHandler client : clients) {
            userList.append(client.getNick()).append(", ");
        }
        String userListMsg = userList.toString();
        for (ClientHandler client : clients) {
            client.sendMessage(userListMsg);
        }
    }

    // broadcast ogólny do klientów
    private void broadcastMessage(String message) {
        for (ClientHandler client : clients) {
            client.sendMessage(message);
        }
        try {
            historyFileWriter.write(message + "\n");
            historyFileWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //
    private class ClientHandler implements Runnable {
        private Socket clientSocket;
        private PrintWriter out; // streams
        private BufferedReader in; // streams
        private String nick;

        public ClientHandler(Socket socket) {
            this.clientSocket = socket;
            try {
                out = new PrintWriter(clientSocket.getOutputStream(), true); // Inicjalizacja strumienia wyjściowego
                in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // Inicjalizacja strumienia wejściowego
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // thread głowny
        public void run() {
            try {
                out.println("Enter your username:");
                String username = in.readLine();
                out.println("Enter your password:");
                String password = in.readLine();

                if (authenticate(username, password)) {
                    nick = username;
                    out.println("Welcome to the chat, " + nick + "!");
                    clients.add(this);
                    broadcastUsers();

                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        System.out.println(nick + ": " + inputLine);

                        if (inputLine.equalsIgnoreCase("exit")) {
                            break;
                        }

                        broadcastMessage(nick + ": " + inputLine); // brdcst wlasniwy
                    }

                    clients.remove(this); // po koncu sesji
                    broadcastUsers();
                } else {
                    out.println("Authentication failed. Incorrect username or password.");
                }

                in.close(); //bezpiecznik przed obsługą wyj
                out.close(); //
                clientSocket.close(); //
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void sendMessage(String message) {
            out.println(message);
        }

        public String getNick() {
            return nick;
        }

        private boolean authenticate(String username, String password) {
            try (BufferedReader br = new BufferedReader(new FileReader("users.txt"))) {
                String line;
                while ((line = br.readLine()) != null) {
                    String[] parts = line.split(":");
                    if (parts.length == 2 && parts[0].equals(username) && parts[1].equals(password)) {
                        return true; // jesli passy ok
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false; // nok
        }
    }

    // MAIN MAIN MAIN
    public static void main(String[] args) {
        int portNumber = 12345; // 12233

        try {
            ChatServer server = new ChatServer(portNumber);
            server.start();
        } catch (IOException e) {
            System.err.println("Error starting the server on port " + portNumber);
            e.printStackTrace();
        }
    }
}
Leave a Comment