1
1
// Copyright (c) .NET Foundation. All rights reserved.
2
2
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3
3
4
- import com .google .gson .Gson ;
5
4
import org .java_websocket .client .WebSocketClient ;
6
5
import org .java_websocket .handshake .ServerHandshake ;
7
6
8
7
import java .net .URI ;
9
8
import java .net .URISyntaxException ;
10
9
11
10
public class WebSocketTransport implements Transport {
12
- private WebSocketClient _webSocket ;
11
+ private WebSocketClient webSocketClient ;
13
12
private OnReceiveCallBack onReceiveCallBack ;
14
- private URI _url ;
13
+ private URI url ;
14
+
15
+ private static final String HTTP = "http" ;
16
+ private static final String HTTPS = "https" ;
17
+ private static final String WS = "ws" ;
18
+ private static final String WSS = "wss" ;
15
19
16
20
public WebSocketTransport (String url ) throws URISyntaxException {
17
- // To Do: Format the incoming URL for a websocket connection.
18
- _url = new URI (url );
19
- _webSocket = createWebSocket ();
21
+ this .url = formatUrl (url );
22
+ }
23
+
24
+ public URI getUrl (){
25
+ return url ;
26
+ }
27
+
28
+ private URI formatUrl (String url ) throws URISyntaxException {
29
+ if (url .startsWith (HTTPS )){
30
+ url = WSS + url .substring (HTTPS .length ());
31
+ }
32
+ else if (url .startsWith (HTTP )){
33
+ url = WS + url .substring (HTTP .length ());
34
+ }
35
+ return new URI (url );
20
36
}
21
37
22
38
@ Override
23
39
public void start () throws InterruptedException {
24
- _webSocket .connectBlocking ();
25
- _webSocket .send ((new DefaultJsonProtocolHandShakeMessage ()).createHandshakeMessage ());
40
+ webSocketClient = createWebSocket ();
41
+ webSocketClient .connectBlocking ();
42
+ webSocketClient .send ((new DefaultJsonProtocolHandShakeMessage ()).createHandshakeMessage ());
26
43
}
27
44
28
45
@ Override
29
46
public void send (String message ) {
30
- _webSocket .send (message );
47
+ webSocketClient .send (message );
31
48
}
32
49
33
50
@ Override
@@ -42,14 +59,14 @@ public void onReceive(String message) throws Exception {
42
59
43
60
@ Override
44
61
public void stop () {
45
- _webSocket .closeConnection (0 , "HubConnection Stopped" );
62
+ webSocketClient .closeConnection (0 , "HubConnection Stopped" );
46
63
}
47
64
48
65
private WebSocketClient createWebSocket () {
49
- return new WebSocketClient (_url ) {
66
+ return new WebSocketClient (url ) {
50
67
@ Override
51
68
public void onOpen (ServerHandshake handshakedata ) {
52
- System .out .println ("Connected to " + _url );
69
+ System .out .println ("Connected to " + url );
53
70
}
54
71
55
72
@ Override
0 commit comments