This repository was archived by the owner on Apr 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathJavaEndpointWebsocket.java
More file actions
99 lines (85 loc) · 2.96 KB
/
JavaEndpointWebsocket.java
File metadata and controls
99 lines (85 loc) · 2.96 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
package io.deepstream;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
class JavaEndpointWebsocket implements Endpoint {
private final URI uri;
private WebSocket websocket;
private final Connection connection;
JavaEndpointWebsocket(URI uri, Connection connection ) throws URISyntaxException {
this.uri = uri;
this.connection = connection;
}
@Override
public void send(String message) {
if (this.websocket.isOpen()) {
this.websocket.send(message);
}
}
@Override
public void close() {
this.websocket.close();
this.websocket = null;
}
@Override
public void forceClose() {
this.websocket.getConnection().closeConnection(1, "Forcing connection close due to network loss");
}
@Override
public void open() {
this.websocket = new WebSocket(this.uri, new Draft_6455());
this.websocket.connect();
}
private class WebSocket extends WebSocketClient {
WebSocket( URI serverUri , Draft draft ) {
super( serverUri, draft );
// Set the SSL context if the socket server is using Secure WebSockets
if (serverUri.toString().startsWith("wss:")) {
SSLContext sslContext;
SSLSocketFactory factory;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, null, null);
factory = sslContext.getSocketFactory();
this.setSocket(factory.createSocket());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (KeyManagementException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@Override
public void onOpen(ServerHandshake handshakedata) {
connection.onOpen();
}
@Override
public void onMessage(String message) {
connection.onMessage( message );
}
@Override
public void onClose(int code, String reason, boolean remote) {
try {
connection.onClose();
} catch( Exception e ) {
}
}
@Override
public void onError(Exception ex) {
if (ex instanceof NullPointerException && ex.getMessage().equals("ssl == null")) {
return;
}
connection.onError( ex.getMessage() );
}
}
}