-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTCP_(2).java
More file actions
44 lines (43 loc) · 1.71 KB
/
TCP_(2).java
File metadata and controls
44 lines (43 loc) · 1.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
import java.nio.charset.StandardCharsets;
import java.nio.charset.StandardCharsets;
public class TCPConnection {
private final Socket socket;
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; // cop
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();
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();
}
}
}