package chat; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class ChatClient { private final String host; private final int port; private Socket socket; private PrintWriter out; private BufferedReader in; private BufferedReader consoleReader; public ChatClient(String host, int port) { this.host = host; this.port = port; this.consoleReader = new BufferedReader(new InputStreamReader(System.in)); } public void start() { try { connectToServer(); MessageListener messageListener = new MessageListener(in); Thread listenerThread = new Thread(messageListener); listenerThread.setDaemon(true); listenerThread.start(); readUserInputAndSend(); } catch (IOException e) { System.err.println("Client error: " + e.getMessage()); } finally { cleanup(); } } private void connectToServer() throws IOException { socket = new Socket(host, port); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); } private void readUserInputAndSend() throws IOException { String line; while((line = consoleReader.readLine()) != null) { out.println(line); } } private void cleanup() { try { if (socket != null && !socket.isClosed()) { socket.close(); } } catch (IOException e) { System.err.println("Error closing socket: " + e.getMessage()); } } public static void main(String[] args) { String host = "127.0.0.1"; int port = 12345; if (args.length > 0) { host = args[0]; } if (args.length > 1) { try { port = Integer.parseInt(args[1]); } catch (NumberFormatException e) { System.err.println("Invalid port. Using default: " + port); } } new ChatClient(host, port).start(); } }