Client

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.2 kB
1
Indexable
Never
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicBoolean;

public class SocketClient {
    public static void main(String[] args) {
        String serverHost = "localhost";
        int serverPort = 8080;

        try (Socket socket = new Socket(serverHost, serverPort);
             BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
             BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in))) {

            AtomicBoolean shouldStop = new AtomicBoolean(false);
            Thread readConsoleThread = new Thread(() -> {
                String request;
                try {
                    while (!shouldStop.get()) {
                        System.out.print("Enter message: ");
                        request = consoleReader.readLine();

                        if (request == null || "quit".equalsIgnoreCase(request)) {
                            shouldStop.set(true);
                            break;
                        }

                        out.println(request);
                        System.out.println("Sent request: " + request);
                    }
                } catch (IOException e) {
                    System.err.println("Error reading from console: " + e.getMessage());
                }
            });

            readConsoleThread.start();

            while (!shouldStop.get()) {
                String response = in.readLine();
                if (response == null) {
                    shouldStop.set(true);
                } else {
                    System.out.println("Received response: " + response);
                }
            }
            readConsoleThread.join();
        } catch (IOException | InterruptedException e) {
            System.err.println("Error connecting to server: " + e.getMessage());
        }
    }
}