blob: 5cbe7f75cbc7f1d312e123d1dec9144ca5b724b6 (
plain)
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
package com.benburwell.planes.sbs;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.List;
import java.util.ArrayList;
/**
* @author ben
*/
public class TCPDataSource implements DataSource {
private List<DataListener> subscribers = new ArrayList<>();
private String host;
private int port;
private Thread clientThread = null;
private SocketClient client = null;
public TCPDataSource(String host, int port) {
this.host = host;
this.port = port;
}
public void subscribe(DataListener listener) {
this.subscribers.add(listener);
}
public void open() {
this.client = new SocketClient(this.host, this.port);
this.clientThread = new Thread(this.client);
this.clientThread.start();
}
public void close() {
if (this.client != null) {
this.client.terminate();
try {
this.clientThread.join();
} catch (InterruptedException ignored) {}
}
}
private class SocketClient implements Runnable {
private String host;
private int port;
private Socket clientSocket = null;
public SocketClient(String host, int port) {
this.host = host;
this.port = port;
}
public void terminate() {
if (this.clientSocket != null) {
try {
this.clientSocket.close();
} catch (IOException e) {
System.out.println("Got exception closing socket: " + e.getMessage());
}
}
}
@Override
public void run() {
System.out.println("Starting socket client");
BufferedReader socketReader;
try {
this.clientSocket = new Socket(this.host, this.port);
} catch (IOException e) {
System.out.println("Could not connect to " + this.host + " on port " + this.port + ": " + e.getMessage());
return;
}
try {
socketReader = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
System.out.println("Could not create socket reader: " + e.getMessage());
return;
}
String receivedMessage;
while (true) {
try {
receivedMessage = socketReader.readLine();
} catch (IOException e) {
System.out.println("Error reading from socket: " + e.getMessage());
return;
}
try {
SBSPacket packet = new SBSPacket(receivedMessage);
for (DataListener subscriber : subscribers) {
subscriber.handleMessage(packet);
}
} catch (MalformedPacketException e) {
System.out.println("Discarding malformed packet: " + receivedMessage);
System.out.println(e.getMessage());
}
}
}
}
}
|