forked from clwillingham/java-socket.io.client
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathIOSocket.java
314 lines (253 loc) · 7.48 KB
/
IOSocket.java
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package com.clwillingham.socket.io;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class IOSocket {
private IOWebSocket webSocket;
private URL connection;
private String sessionID;
private int heartTimeout;
private int closingTimeout;
private int connectTimeout = 10000;
private String[] protocals;
private final String webSocketAddress;
private final String namespace;
private final MessageCallback callback;
private Timer timer;
private int ackCount = 0;
private HashMap<Integer, AckCallback> ackCallbacks = new HashMap<Integer, AckCallback>();
private boolean connecting;
private boolean connected;
private boolean open;
public IOSocket(String address, MessageCallback callback){
// check for socket.io namespace
int i = address.lastIndexOf("/");
if (address.charAt(i-1) != '/') {
namespace = address.substring(i);
webSocketAddress = address.substring(0, i);
} else {
namespace = "";
webSocketAddress = address;
}
this.callback = callback;
}
public void connect() {
synchronized(this) {
connecting = true;
}
timer = new Timer();
timer.schedule(new ConnectTimeout(), connectTimeout);
(new Thread(new Handshake())).start();
}
public void emit(String event, JSONObject... message) throws IOException {
try {
JSONObject data = new JSONObject();
JSONArray args = new JSONArray();
for (JSONObject arg : message) {
args.put(arg);
}
data.put("name", event);
data.put("args", args);
IOMessage packet = new IOMessage(IOMessage.EVENT, "", data.toString());
webSocket.sendMessage(packet);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void emit(String event, JSONObject message, AckCallback callback) throws IOException {
try {
JSONObject data = new JSONObject();
data.put("name", event);
data.put("args", message);
IOMessage packet = new IOMessage(IOMessage.EVENT, addAcknowledge(callback, message), "", data.toString());
packet.setAck(true);
webSocket.sendMessage(packet);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void send(String message) throws IOException {
IOMessage packet = new IOMessage(IOMessage.MESSAGE, "", message);
webSocket.sendMessage(packet);
}
public synchronized void disconnect() {
if (connected) {
try {
if (open) {
webSocket.sendMessage(new IOMessage(IOMessage.DISCONNECT, "", ""));
}
} catch (IOException e) {
e.printStackTrace();
}
onDisconnect();
}
}
synchronized void onOpen() {
open = true;
}
synchronized void onClose() {
open = false;
}
synchronized void onConnect() {
if (!connected) {
connected = true;
connecting = false;
callback.onConnect();
}
}
synchronized void onDisconnect() {
boolean wasConnected = connected;
connected = false;
connecting = false;
if (open) {
try {
webSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (wasConnected) {
callback.onDisconnect();
//TODO: reconnect
}
}
private synchronized void onConnectFailure() {
connecting = false;
connected = false;
callback.onConnectFailure();
}
public void onAcknowledge(int ackId, JSONArray data) {
AckCallback ackCallback = ackCallbacks.get(ackId);
if (ackCallback != null) {
try {
ackCallback.callback(data);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ackCallbacks.remove(ackId);
}
}
public synchronized boolean isConnected() {
return connected;
}
public synchronized boolean isConnecting() {
return connecting;
}
public boolean isOpen() {
return open;
}
public void setConnection(URL connection) {
this.connection = connection;
}
private int addAcknowledge(AckCallback cb, JSONObject message) {
if (cb != null) {
cb.setRequestData(message);
ackCount++;
ackCallbacks.put(ackCount, cb);
return ackCount;
}
return -1;
}
public URL getConnection() {
return connection;
}
public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}
public int getConnectTimeout() {
return connectTimeout;
}
public void setHeartTimeout(int heartTimeOut) {
this.heartTimeout = heartTimeOut;
}
public int getHeartTimeout() {
return heartTimeout;
}
public void setClosingTimeout(int closingTimeout) {
this.closingTimeout = closingTimeout;
}
public int getClosingTimeout() {
return closingTimeout;
}
public void setSessionID(String sessionID) {
this.sessionID = sessionID;
}
public String getSessionID() {
return sessionID;
}
public void setProtocals(String[] protocals) {
this.protocals = protocals;
}
public String[] getProtocals() {
return protocals;
}
private synchronized void onHandshakeSuccess() {
if (!connecting) {
return;
}
webSocket = new IOWebSocket(URI.create(webSocketAddress+"/socket.io/1/websocket/"+sessionID), this, callback);
webSocket.setNamespace(namespace);
webSocket.connect();
}
private class Handshake implements Runnable {
@Override
public void run() {
try {
String address = webSocketAddress.replace("ws://", "http://");
URL url = new URL(address + "/socket.io/1/"); //handshake url
URLConnection connection = url.openConnection();
connection.setConnectTimeout(connectTimeout);
connection.setReadTimeout(connectTimeout);
InputStream stream = connection.getInputStream();
Scanner in = new Scanner(stream);
String response = in.nextLine(); //pull the response
// process handshake response
// example: 4d4f185e96a7b:15:10:websocket,xhr-polling
if(response.contains(":")) {
String[] data = response.split(":");
setSessionID(data[0]);
setHeartTimeout(Integer.parseInt(data[1]) * 1000);
setClosingTimeout(Integer.parseInt(data[2]) * 1000);
setProtocals(data[3].split(","));
onHandshakeSuccess();
} else {
onConnectFailure();
}
} catch (IOException e) {
onConnectFailure();
}
}
}
private class ConnectTimeout extends TimerTask {
@Override
public void run() {
synchronized(IOSocket.this) {
if (connected || !connecting) {
return;
}
connecting = false;
if (webSocket != null) {
try {
webSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
onConnectFailure();
}
}
}
}