Files
WS-10-Network/src/main/java/chat/ChatClient.java
T
2026-06-07 10:23:19 +03:30

73 lines
2.0 KiB
Java

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 {
// TODO: create socket connection to host:port
// TODO: initialize output stream (PrintWriter)
// TODO: initialize input stream (BufferedReader)
}
private void readUserInputAndSend() throws IOException {
// TODO: read continuously from console
// TODO: send each input line to server
}
private void cleanup() {
// TODO: close socket safely
// TODO: release resources
}
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();
}
}