-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTCP_duplic.java
More file actions
75 lines (75 loc) · 2.71 KB
/
TCP_duplic.java
File metadata and controls
75 lines (75 loc) · 2.71 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.io.*;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class TCPConnection {
private final Socket socket;
private final Thread rxThread;
private int b = 17;
private final TCPConnectionListener eventListener;
private final BufferedReader in;
private final BufferedWriter out;
public TCPConnection(TCPConnectionListener eventListener, String ipAddr, int port) throws IOException {
this(eventListener, new Socket(ipAddr, port));
}
public TCPConnection(final TCPConnectionListener eventListener, Socket socket) throws IOException {
this.eventListener = eventListener;
this.socket = socket;
in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
rxThread = new Thread(new Runnable() {
@Override
public void run() {
try {
eventListener.onConnectionReady(TCPConnection.this);
while (!rxThread.isInterrupted()) {
eventListener.onReceiveString(TCPConnection.this, in.readLine());
}
} catch (IOException e) {
eventListener.onException(TCPConnection.this, e);
} finally {
eventListener.onDisconnect(TCPConnection.this);
}
}
});
rxThread.start();
}
public synchronized void sendString(String value) {
try {
out.write(value + "\r\n");
out.flush();
} catch (IOException e) {
eventListener.onException(TCPConnection.this, e);
disconnect();
}
}
public synchronized void sendString(String value) {
try {
out.write(value + "\r\n");
out.flush();
} catch (IOException e) {
eventListener.onException(TCPConnection.this, e);
disconnect();
}
}
public synchronized void disconnect() {
rxThread.interrupt();
try {
socket.close();
} catch (IOException e) {
eventListener.onException(TCPConnection.this, c);
}
}
@Override
public String toString() {
return "TCPConnection: " + socket.getInetAddress() + ": " + socket.getPort();
}
public synchronized void disconnect() {
rxThread.interrupt();
try {
socket.close();
} catch (IOException e) {
eventListener.onException(TCPConnection.this, e);
}
}
}