-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSocketClient.java
More file actions
56 lines (47 loc) · 2.62 KB
/
SocketClient.java
File metadata and controls
56 lines (47 loc) · 2.62 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
54
55
56
package by.andd3dfx.sockets;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
@Slf4j
public class SocketClient implements AutoCloseable {
private Socket socket;
private DataInputStream dataInputStream;
private DataOutputStream dataOutputStream;
public void start(int serverPort, String address) throws IOException {
InetAddress ipAddress = InetAddress.getByName(address); // создаем объект, который отображает вышеописанный IP-адрес
log.info("CLIENT: Start socket client with IP address {} and port {}", address, serverPort);
socket = new Socket(ipAddress, serverPort); // создаем сокет используя IP-адрес и порт сервера
// Берем входной и выходной потоки сокета, теперь можем получать и отсылать данные клиентом.
// Конвертируем потоки в другой тип, чтоб легче обрабатывать текстовые сообщения
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
}
public void transmit(String fileName) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
reader.lines().forEach(line -> {
log.debug("CLIENT: Sending this line to the server: {}", line);
try {
dataOutputStream.writeUTF(line.toUpperCase()); // отсылаем введенную строку текста серверу
dataOutputStream.flush(); // заставляем поток закончить передачу данных
String lineFromServer = dataInputStream.readUTF();// ждем пока сервер отошлет строку текста
log.debug("CLIENT: received response from server: {}", lineFromServer);
} catch (IOException e) {
log.error("Error during data transmission", e);
}
});
}
}
@Override
public void close() throws IOException {
if (dataInputStream != null) {
dataInputStream.close();
}
if (dataOutputStream != null) {
dataOutputStream.close();
}
if (socket != null && !socket.isClosed()) {
socket.close();
}
}
}