64 lines
2.4 KiB
Java
64 lines
2.4 KiB
Java
package client;
|
||
|
||
import java.io.BufferedReader;
|
||
import java.io.IOException;
|
||
import java.io.InputStreamReader;
|
||
import java.io.PrintWriter;
|
||
import java.net.Socket;
|
||
|
||
public class ConsoleManager {
|
||
private final Socket socket;
|
||
private final PrintWriter out;
|
||
private final BufferedReader in;
|
||
private final BufferedReader consoleReader;
|
||
|
||
public ConsoleManager(String host, int port) throws IOException {
|
||
this.socket = new Socket(host, port);
|
||
this.out = new PrintWriter(socket.getOutputStream(), true);
|
||
this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
|
||
this.consoleReader = new BufferedReader(new InputStreamReader(System.in));
|
||
}
|
||
|
||
public void run() {
|
||
System.out.println("Клиент запущен. Введите команду (введите 'exit' для выхода):");
|
||
|
||
try {
|
||
while (true) {
|
||
String userInput = consoleReader.readLine();
|
||
|
||
if (userInput != null && !userInput.isEmpty()) {
|
||
out.println(userInput); // Отправляем команду на сервер
|
||
|
||
if ("exit".equalsIgnoreCase(userInput)) {
|
||
// Клиент закрыл соединение, но сервер должен продолжать работать
|
||
break;
|
||
}
|
||
|
||
String response = in.readLine(); // Читаем ответ от сервера
|
||
System.out.println("Ответ сервера: " + response);
|
||
}
|
||
}
|
||
} catch (IOException e) {
|
||
System.out.println("Ошибка при общении с сервером: " + e.getMessage());
|
||
} finally {
|
||
try {
|
||
socket.close();
|
||
out.close();
|
||
in.close();
|
||
consoleReader.close();
|
||
} catch (IOException e) {
|
||
System.out.println("Ошибка при закрытии ресурсов: " + e.getMessage());
|
||
}
|
||
}
|
||
}
|
||
|
||
public static void main(String[] args) {
|
||
try {
|
||
ConsoleManager consoleManager = new ConsoleManager("localhost", 4444);
|
||
consoleManager.run();
|
||
} catch (IOException e) {
|
||
System.out.println("Не удалось подключиться к серверу: " + e.getMessage());
|
||
}
|
||
}
|
||
}
|