-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClientConnectionHandler.java
More file actions
53 lines (45 loc) · 1.7 KB
/
Copy pathClientConnectionHandler.java
File metadata and controls
53 lines (45 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package io.github.winroot33;
import lombok.RequiredArgsConstructor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
/**
* Класс для обработки соединений с клиентами, Runnable для передачи в пул потоков
*/
@RequiredArgsConstructor
public class ClientConnectionHandler implements Runnable {
private final Socket clientSocket;
@Override
public void run() {
handleConnection();
}
/**
* Обработка нового соединения
*/
private void handleConnection() {
try (Socket socket = this.clientSocket;
PrintWriter out = new PrintWriter(socket.getOutputStream(), true, StandardCharsets.UTF_8);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8))) {
processClientMessages(in, out);
} catch (IOException e) {
System.err.println("IO Error: " + e.getMessage());
}
}
/**
* Метод для отправки эхо сообщений пользователю
*
* @param in входной поток данных
* @param out выходной поток
*/
private void processClientMessages(BufferedReader in, PrintWriter out) throws IOException {
String inputLine;
while ((inputLine = in.readLine()) != null) {
out.println(inputLine);
System.out.printf("Thread: %s\tMessage sent: %s\n", Thread.currentThread().getName(), inputLine);
}
}
}