-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathSocket.java
More file actions
638 lines (544 loc) · 21.6 KB
/
Socket.java
File metadata and controls
638 lines (544 loc) · 21.6 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
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
package io.github.sac;
import com.neovisionaries.ws.client.OpeningHandshakeException;
import com.neovisionaries.ws.client.StatusLine;
import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketAdapter;
import com.neovisionaries.ws.client.WebSocketException;
import com.neovisionaries.ws.client.WebSocketFactory;
import com.neovisionaries.ws.client.WebSocketFrame;
import com.neovisionaries.ws.client.WebSocketState;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by sachin on 13/11/16.
*/
public class Socket extends Emitter {
private final Logger logger = Logger.getLogger(Socket.class.getName());
private AtomicInteger counter;
private String URL;
private WebSocketFactory factory;
private ReconnectStrategy strategy;
private WebSocket ws;
private BasicListener listener;
private String AuthToken;
private HashMap<Long, Object[]> acks;
private ConcurrentHashMap<String, Channel> channels;
private WebSocketAdapter adapter;
private Map<String, String> headers;
public Socket(String URL) {
this.URL = URL;
factory = new WebSocketFactory().setConnectionTimeout(5000);
counter = new AtomicInteger(1);
acks = new HashMap<>();
channels = new ConcurrentHashMap<>();
adapter = getAdapter();
headers = new HashMap<>();
putDefaultHeaders();
}
private void putDefaultHeaders() {
headers.put("Accept-Encoding", "gzip, deflate, sdch");
headers.put("Accept-Language", "en-US,en;q=0.8");
headers.put("Pragma", "no-cache");
headers.put("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36");
}
public Channel createChannel(String name) {
if(channels.containsKey(name)){
return channels.get(name);
}
Channel channel = new Channel(name);
channels.put(name, channel);
return channel;
}
public ConcurrentHashMap<String, Channel> getChannels() {
return channels;
}
public Channel getChannelByName(String name) {
channels.get(name);
return null;
}
public void seturl(String url) {
this.URL = url;
}
public void setReconnection(ReconnectStrategy strategy) {
this.strategy = strategy;
}
public void setListener(BasicListener listener) {
this.listener = listener;
}
public Logger getLogger(){
return logger;
}
/**
* used to set up TLS/SSL connection to server for more details visit neovisionaries websocket client
*/
public WebSocketFactory getFactorySettings() {
return factory;
}
public void setAuthToken(String token) {
AuthToken = token;
}
public WebSocketAdapter getAdapter() {
return new WebSocketAdapter() {
@Override
public void onConnected(WebSocket websocket, Map<String, List<String>> headers) throws Exception {
/**
* Code for sending handshake
*/
counter.set(1);
if (strategy != null) {
strategy.setAttemptsMade(0);
}
JSONObject handshakeObject = new JSONObject();
handshakeObject.put("event", "#handshake");
JSONObject object = new JSONObject();
object.put("authToken", AuthToken);
handshakeObject.put("data", object);
handshakeObject.put("cid", counter.getAndIncrement());
websocket.sendText(handshakeObject.toString());
listener.onConnected(Socket.this, headers);
super.onConnected(websocket, headers);
}
@Override
public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception {
listener.onDisconnected(Socket.this, serverCloseFrame, clientCloseFrame, closedByServer);
reconnect();
super.onDisconnected(websocket, serverCloseFrame, clientCloseFrame, closedByServer);
}
@Override
public void onConnectError(WebSocket websocket, WebSocketException exception) throws Exception {
listener.onConnectError(Socket.this, exception);
reconnect();
super.onConnectError(websocket, exception);
}
@Override
public void onTextMessage(WebSocket websocket, String text) throws Exception {
if (text == null) {
websocket.sendText("");
}
super.onTextMessage(websocket, text);
}
@Override
public void onFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
JSONObject object = new JSONObject(frame.getPayloadText());
/**
* Message retrieval mechanism goes here
*/
logger.info("Message :" + object.toString());
try {
Object dataobject = object.opt("data");
Integer rid = (Integer) object.opt("rid");
Integer cid = (Integer) object.opt("cid");
String event = (String) object.opt("event");
switch (Parser.parse(dataobject, event)) {
case ISAUTHENTICATED:
listener.onAuthentication(Socket.this, ((JSONObject) dataobject).getBoolean("isAuthenticated"));
subscribeChannels();
break;
case PUBLISH:
Socket.this.handlePublish(((JSONObject) dataobject).getString("channel"), ((JSONObject) dataobject).opt("data"));
break;
case REMOVETOKEN:
setAuthToken(null);
break;
case SETTOKEN:
String token = ((JSONObject) dataobject).getString("token");
setAuthToken(token);
listener.onSetAuthToken(token, Socket.this);
break;
case EVENT:
if (hasEventAck(event)) {
handleEmitAck(event, dataobject, ack(Long.valueOf(cid)));
} else {
Socket.this.handleEmit(event, dataobject);
}
break;
case ACKRECEIVE:
if (acks.containsKey((long) rid)) {
Object[] objects = acks.remove((long) rid);
if (objects != null) {
Ack fn = (Ack) objects[1];
if (fn != null) {
fn.call((String) objects[0], object.opt("error"), object.opt("data"));
} else {
logger.warning("ack function is null with rid " + rid);
}
}
}
break;
}
} catch (Exception e) {
logger.severe(e.toString());
}
super.onFrame(websocket, frame);
}
@Override
public void onCloseFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
logger.warning("On close frame got called");
super.onCloseFrame(websocket, frame);
}
@Override
public void onSendError(WebSocket websocket, WebSocketException cause, WebSocketFrame frame) throws Exception {
logger.severe("Error while sending data " + cause.toString());
super.onSendError(websocket, cause, frame);
}
};
}
public Socket emit(final String event, final Object object) {
EventThread.exec(new Runnable() {
public void run() {
JSONObject eventObject = new JSONObject();
try {
eventObject.put("event", event);
eventObject.put("data", object);
} catch (JSONException e) {
e.printStackTrace();
}
ws.sendText(eventObject.toString());
}
});
return this;
}
public Socket emit(final String event, final Object object, final Ack ack) {
EventThread.exec(new Runnable() {
public void run() {
JSONObject eventObject = new JSONObject();
acks.put(counter.longValue(), getAckObject(event, ack));
try {
eventObject.put("event", event);
eventObject.put("data", object);
eventObject.put("cid", counter.getAndIncrement());
} catch (JSONException e) {
e.printStackTrace();
}
ws.sendText(eventObject.toString());
}
});
return this;
}
private Socket subscribe(final String channel) {
EventThread.exec(new Runnable() {
public void run() {
JSONObject subscribeObject = new JSONObject();
try {
subscribeObject.put("event", "#subscribe");
JSONObject object = new JSONObject();
object.put("channel", channel);
subscribeObject.put("data", object);
subscribeObject.put("cid", counter.getAndIncrement());
} catch (JSONException e) {
e.printStackTrace();
}
ws.sendText(subscribeObject.toString());
}
});
return this;
}
private Object[] getAckObject(String event, Ack ack) {
Object object[] = {event, ack};
return object;
}
private Socket subscribe(final String channel, final Ack ack) {
EventThread.exec(new Runnable() {
public void run() {
JSONObject subscribeObject = new JSONObject();
try {
subscribeObject.put("event", "#subscribe");
JSONObject object = new JSONObject();
acks.put(counter.longValue(), getAckObject(channel, ack));
object.put("channel", channel);
subscribeObject.put("data", object);
subscribeObject.put("cid", counter.getAndIncrement());
} catch (JSONException e) {
e.printStackTrace();
}
ws.sendText(subscribeObject.toString());
}
});
return this;
}
private Socket subscribe(final String channel, JSONObject object, final Ack ack) {
EventThread.exec(new Runnable() {
public void run() {
JSONObject subscribeObject = new JSONObject();
try {
subscribeObject.put("event", "#subscribe");
acks.put(counter.longValue(), getAckObject(channel, ack));
object.put("channel", channel);
subscribeObject.put("data", object);
subscribeObject.put("cid", counter.getAndIncrement());
} catch (JSONException e) {
e.printStackTrace();
}
ws.sendText(subscribeObject.toString());
}
});
return this;
}
private Socket unsubscribe(final String channel) {
EventThread.exec(new Runnable() {
public void run() {
JSONObject subscribeObject = new JSONObject();
try {
subscribeObject.put("event", "#unsubscribe");
subscribeObject.put("data", channel);
subscribeObject.put("cid", counter.getAndIncrement());
} catch (JSONException e) {
e.printStackTrace();
}
ws.sendText(subscribeObject.toString());
}
});
return this;
}
private Socket unsubscribe(final String channel, final Ack ack) {
EventThread.exec(new Runnable() {
public void run() {
JSONObject subscribeObject = new JSONObject();
try {
subscribeObject.put("event", "#unsubscribe");
subscribeObject.put("data", channel);
acks.put(counter.longValue(), getAckObject(channel, ack));
subscribeObject.put("cid", counter.getAndIncrement());
} catch (JSONException e) {
e.printStackTrace();
}
ws.sendText(subscribeObject.toString());
}
});
return this;
}
public Socket publish(final String channel, final Object data) {
EventThread.exec(new Runnable() {
public void run() {
JSONObject publishObject = new JSONObject();
try {
publishObject.put("event", "#publish");
JSONObject object = new JSONObject();
object.put("channel", channel);
object.put("data", data);
publishObject.put("data", object);
publishObject.put("cid", counter.getAndIncrement());
} catch (JSONException e) {
e.printStackTrace();
}
ws.sendText(publishObject.toString());
}
});
return this;
}
public Socket publish(final String channel, final Object data, final Ack ack) {
EventThread.exec(new Runnable() {
public void run() {
JSONObject publishObject = new JSONObject();
try {
publishObject.put("event", "#publish");
JSONObject object = new JSONObject();
acks.put(counter.longValue(), getAckObject(channel, ack));
object.put("channel", channel);
object.put("data", data);
publishObject.put("data", object);
publishObject.put("cid", counter.getAndIncrement());
} catch (JSONException e) {
e.printStackTrace();
}
ws.sendText(publishObject.toString());
}
});
return this;
}
private Ack ack(final Long cid) {
return new Ack() {
public void call(final String channel, final Object error, final Object data) {
EventThread.exec(new Runnable() {
public void run() {
JSONObject object = new JSONObject();
try {
object.put("error", error);
object.put("data", data);
object.put("rid", cid);
} catch (JSONException e) {
e.printStackTrace();
}
ws.sendText(object.toString());
}
});
}
};
}
private void subscribeChannels() {
for(Map.Entry<String, Channel> entry : channels.entrySet()) {
entry.getValue().subscribe();
}
}
public void setExtraHeaders(Map<String, String> extraHeaders, boolean overrideDefaultHeaders) {
if (overrideDefaultHeaders) {
headers.clear();
}
headers.putAll(extraHeaders);
}
public Map<String, String> getHeaders() {
return headers;
}
public void connect() {
try {
ws = factory.createSocket(URL);
} catch (IOException e) {
logger.severe(e.toString());
}
ws.addExtension("permessage-deflate; client_max_window_bits");
for (Map.Entry<String, String> entry : headers.entrySet()) {
ws.addHeader(entry.getKey(), entry.getValue());
}
ws.addListener(adapter);
try {
ws.connect();
} catch (OpeningHandshakeException e) {
// A violation against the WebSocket protocol was detected
// during the opening handshake.
logger.severe(e.toString());
// Status line.
StatusLine sl = e.getStatusLine();
logger.info("=== Status Line ===");
logger.info("HTTP Version = \n" + sl.getHttpVersion());
logger.info("Status Code = \n" + sl.getStatusCode());
logger.info("Reason Phrase = \n" + sl.getReasonPhrase());
// HTTP headers.
Map<String, List<String>> headers = e.getHeaders();
logger.info("=== HTTP Headers ===");
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
// Header name.
String name = entry.getKey();
// Values of the header.
List<String> values = entry.getValue();
if (values == null || values.size() == 0) {
// Print the name only.
logger.info(name);
continue;
}
for (String value : values) {
// Print the name and the value.
logger.info(name + value + "\n");
}
}
} catch (WebSocketException e) {
listener.onConnectError(Socket.this, e);
reconnect();
}
}
public void connectAsync() {
try {
ws = factory.createSocket(URL);
} catch (IOException e) {
logger.severe(e.toString());
}
ws.addExtension("permessage-deflate; client_max_window_bits");
for (Map.Entry<String, String> entry : headers.entrySet()) {
ws.addHeader(entry.getKey(), entry.getValue());
}
ws.addListener(adapter);
ws.connectAsynchronously();
}
private void reconnect() {
if (strategy == null) {
logger.warning("Unable to reconnect: reconnection is null");
return;
}
if (strategy.areAttemptsComplete()) {
strategy.setAttemptsMade(0);
logger.warning("Unable to reconnect: max reconnection attempts reached");
return;
}
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
if (strategy == null) {
logger.warning("Unable to reconnect: reconnection is null");
return;
}
strategy.processValues();
Socket.this.connect();
timer.cancel();
timer.purge();
}
}, strategy.getReconnectInterval());
}
public void disconnect() {
if (ws != null) {
ws.disconnect();
}
strategy = null;
}
/**
* States can be
* CLOSED
* CLOSING
* CONNECTING
* CREATED
* OPEN
*/
public WebSocketState getCurrentState() {
return ws != null ? ws.getState() : null;
}
public Boolean isconnected() {
return ws != null && ws.getState() == WebSocketState.OPEN;
}
public void disableLogging() {
logger.setLevel(Level.OFF);
}
/**
* Channels need to be subscribed everytime whenever client is reconnected to server (handled inside)
* Add only one listener to one channel for whole lifetime of process
*/
public class Channel {
String channelName;
public String getChannelName() {
return channelName;
}
public Channel(String channelName) {
this.channelName = channelName;
}
public void subscribe() {
Socket.this.subscribe(channelName);
}
public void subscribe(Ack ack) {
Socket.this.subscribe(channelName, ack);
}
public void subscribe(JSONObject object, Ack ack) {
Socket.this.subscribe(channelName, object, ack);
}
public void onMessage(Listener listener) {
Socket.this.onSubscribe(channelName, listener);
}
public void publish(Object data) {
Socket.this.publish(channelName, data);
}
public void publish(Object data, Ack ack) {
Socket.this.publish(channelName, data, ack);
}
public void unsubscribe() {
Socket.this.unsubscribe(channelName);
channels.remove(this);
}
public void unsubscribe(Ack ack) {
Socket.this.unsubscribe(channelName, ack);
channels.remove(this);
}
}
@Override
protected void finalize() throws Throwable {
ws.disconnect("Client socket garbage collected, closing connection");
super.finalize();
}
}