Skip to content

Commit 27f27cf

Browse files
committed
Changes to connect and disconnect methods
1 parent a30a79c commit 27f27cf

File tree

6 files changed

+107
-66
lines changed

6 files changed

+107
-66
lines changed

app/src/main/java/com/smartarmenia/websocketclient/MainActivity.kt

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,21 +29,29 @@ class MainActivity : AppCompatActivity(), HubConnectionListener, HubEventListene
2929
runOnUiThread { Toast.makeText(this@MainActivity, exception.message, Toast.LENGTH_SHORT).show() }
3030
}
3131

32-
private val connection: HubConnection = WebSocketHubConnection("http://192.168.0.104:5002/signalr/hubs/auth")
32+
private val authHeader = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6Ijc5NzhjMjI3LWViMGItNGMwOS1iYWEyLTEwYmE0MjI4YWE4OSIsImNlcnRzZXJpYWxudW1iZXIiOiJtYWNfYWRkcmVzc19vZl9waG9uZSIsInNlY3VyaXR5U3RhbXAiOiJlMTAxOWNiYy1jMjM2LTQ0ZTEtYjdjYy0zNjMxYTYxYzMxYmIiLCJuYmYiOjE1MDYyODQ4NzMsImV4cCI6NDY2MTk1ODQ3MywiaWF0IjoxNTA2Mjg0ODczLCJpc3MiOiJCbGVuZCIsImF1ZCI6IkJsZW5kIn0.QUh241IB7g3axLcfmKR2899Kt1xrTInwT6BBszf6aP4"
33+
private val connection: HubConnection = WebSocketHubConnection("http://192.168.0.104:5002/signalr/hubs/auth", authHeader)
3334

3435
override fun onCreate(savedInstanceState: Bundle?) {
3536
super.onCreate(savedInstanceState)
3637
setContentView(R.layout.activity_main)
3738

38-
btnHello.setOnClickListener {
39+
connection.addListener(this@MainActivity)
40+
connection.subscribeToEvent("Send", this)
41+
42+
btnSendMessage.setOnClickListener {
3943
try {
4044
connection.invoke("Send", "Hello")
4145
} catch (e: Exception) {
4246
Toast.makeText(this@MainActivity, e.message, Toast.LENGTH_SHORT).show()
4347
}
4448
}
4549

46-
connect()
50+
btnConnect.setOnClickListener {
51+
connect()
52+
}
53+
54+
btnDisconnect.setOnClickListener { connection.disconnect() }
4755
}
4856

4957
override fun onDestroy() {
@@ -55,11 +63,9 @@ class MainActivity : AppCompatActivity(), HubConnectionListener, HubEventListene
5563

5664
private fun connect() {
5765
try {
58-
connection.connect("Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6Ijc5NzhjMjI3LWViMGItNGMwOS1iYWEyLTEwYmE0MjI4YWE4OSIsImNlcnRzZXJpYWxudW1iZXIiOiJtYWNfYWRkcmVzc19vZl9waG9uZSIsInNlY3VyaXR5U3RhbXAiOiJlMTAxOWNiYy1jMjM2LTQ0ZTEtYjdjYy0zNjMxYTYxYzMxYmIiLCJuYmYiOjE1MDYyODQ4NzMsImV4cCI6NDY2MTk1ODQ3MywiaWF0IjoxNTA2Mjg0ODczLCJpc3MiOiJCbGVuZCIsImF1ZCI6IkJsZW5kIn0.QUh241IB7g3axLcfmKR2899Kt1xrTInwT6BBszf6aP4")
66+
connection.connect()
5967
} catch (ex: Exception) {
6068
runOnUiThread { Toast.makeText(this@MainActivity, ex.message, Toast.LENGTH_SHORT).show() }
6169
}
62-
connection.addListener(this@MainActivity)
63-
connection.subscribeToEvent("Send", this)
6470
}
6571
}
Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,27 @@
11
<?xml version="1.0" encoding="utf-8"?>
2-
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
3-
xmlns:app="http://schemas.android.com/apk/res-auto"
2+
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
43
xmlns:tools="http://schemas.android.com/tools"
54
android:layout_width="match_parent"
65
android:layout_height="match_parent"
6+
android:orientation="vertical"
77
tools:context="com.smartarmenia.websocketclient.MainActivity">
88

99
<android.support.v7.widget.AppCompatButton
10-
android:id="@+id/btnHello"
11-
android:layout_width="wrap_content"
10+
android:id="@+id/btnConnect"
11+
android:layout_width="match_parent"
1212
android:layout_height="wrap_content"
13-
android:text="Hello World!"
14-
app:layout_constraintBottom_toBottomOf="parent"
15-
app:layout_constraintLeft_toLeftOf="parent"
16-
app:layout_constraintRight_toRightOf="parent"
17-
app:layout_constraintTop_toTopOf="parent" />
13+
android:text="Connect" />
1814

19-
</android.support.constraint.ConstraintLayout>
15+
<android.support.v7.widget.AppCompatButton
16+
android:id="@+id/btnDisconnect"
17+
android:layout_width="match_parent"
18+
android:layout_height="wrap_content"
19+
android:text="Disconnect" />
20+
21+
<android.support.v7.widget.AppCompatButton
22+
android:id="@+id/btnSendMessage"
23+
android:layout_width="match_parent"
24+
android:layout_height="wrap_content"
25+
android:text="Send Message" />
26+
27+
</LinearLayout>

dotnetcoresignalrclientjava/bintray.gradle

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
apply plugin: 'com.jfrog.bintray'
22

3-
version = '1.07'
3+
version = '1.08'
44

55
task sourcesJar(type: Jar) {
66
from android.sourceSets.main.java.srcDirs

dotnetcoresignalrclientjava/build.gradle

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ android {
88
defaultConfig {
99
minSdkVersion 16
1010
targetSdkVersion 26
11-
versionCode 8
12-
versionName "1.07"
11+
versionCode 9
12+
versionName "1.08"
1313
}
1414

1515
buildTypes {

dotnetcoresignalrclientjava/src/main/java/com/smartarmenia/dotnetcoresignalrclientjava/HubConnection.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package com.smartarmenia.dotnetcoresignalrclientjava;
22

33
public interface HubConnection {
4-
void connect(String authHeader);
4+
void connect();
55

66
void disconnect();
77

dotnetcoresignalrclientjava/src/main/java/com/smartarmenia/dotnetcoresignalrclientjava/WebSocketHubConnection.java

Lines changed: 73 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -35,22 +35,38 @@ public class WebSocketHubConnection implements HubConnection {
3535
private String hubUrl;
3636
private Gson gson = new Gson();
3737

38-
public WebSocketHubConnection(String hubUrl) {
38+
private String connectionId = null;
39+
private String authHeader = null;
40+
41+
public WebSocketHubConnection(String hubUrl, String authHeader) {
3942
this.hubUrl = hubUrl;
43+
this.authHeader = authHeader;
4044
parsedUri = Uri.parse(hubUrl);
4145
}
4246

4347
@Override
44-
public void connect(final String authHeader) {
45-
Runnable runnable = new Runnable() {
46-
public void run() {
47-
getConnectionId(authHeader);
48-
}
49-
};
48+
public synchronized void connect() {
49+
if (client != null && (client.isOpen() || client.isConnecting()))
50+
return;
51+
52+
Runnable runnable;
53+
if (connectionId == null) {
54+
runnable = new Runnable() {
55+
public void run() {
56+
getConnectionId();
57+
}
58+
};
59+
} else {
60+
runnable = new Runnable() {
61+
public void run() {
62+
connectClient();
63+
}
64+
};
65+
}
5066
new Thread(runnable).start();
5167
}
5268

53-
private void getConnectionId(String authHeader) {
69+
private void getConnectionId() {
5470
Log.i(TAG, "Requesting connection id...");
5571
if (!(parsedUri.getScheme().equals("http") || parsedUri.getScheme().equals("https")))
5672
throw new RuntimeException("URL must start with http or https");
@@ -75,18 +91,23 @@ private void getConnectionId(String authHeader) {
7591
if (!availableTransports.contains("WebSockets")) {
7692
throw new RuntimeException("The server does not support WebSockets transport");
7793
}
78-
connectClient(connectionId, authHeader);
94+
this.connectionId = connectionId;
95+
connectClient();
7996
} else if (responseCode == 401) {
80-
throw new RuntimeException("Unauthorized request");
97+
RuntimeException runtimeException = new RuntimeException("Unauthorized request");
98+
error(runtimeException);
99+
throw runtimeException;
81100
} else {
82-
throw new RuntimeException("Server error");
101+
RuntimeException runtimeException = new RuntimeException("Server error");
102+
error(runtimeException);
103+
throw runtimeException;
83104
}
84105
} catch (Exception e) {
85106
e.printStackTrace();
86107
}
87108
}
88109

89-
private void connectClient(String connectionId, String authHeader) throws Exception {
110+
private void connectClient() {
90111
Uri.Builder uriBuilder = parsedUri.buildUpon();
91112
uriBuilder.appendQueryParameter("id", connectionId);
92113
uriBuilder.scheme(parsedUri.getScheme().replace("http", "ws"));
@@ -95,49 +116,55 @@ private void connectClient(String connectionId, String authHeader) throws Except
95116
if (authHeader != null && !authHeader.isEmpty()) {
96117
headers.put("Authorization", authHeader);
97118
}
98-
client = new WebSocketClient(new URI(uri.toString()), new Draft_6455(), headers, 15000) {
99-
@Override
100-
public void onOpen(ServerHandshake handshakedata) {
101-
Log.i(TAG, "Opened");
102-
for (HubConnectionListener listener : listeners) {
103-
listener.onConnected();
104-
}
105-
send("{\"protocol\":\"json\"}" + SPECIAL_SYMBOL);
106-
}
107-
108-
@Override
109-
public void onMessage(String message) {
110-
Log.i(TAG, message);
111-
SignalRMessage element = gson.fromJson(message.replace(SPECIAL_SYMBOL, ""), SignalRMessage.class);
112-
if (element.getType() == 1) {
113-
HubMessage hubMessage = new HubMessage(element.getInvocationId(), element.getTarget(), element.getArguments());
119+
try {
120+
client = new WebSocketClient(new URI(uri.toString()), new Draft_6455(), headers, 15000) {
121+
@Override
122+
public void onOpen(ServerHandshake handshakedata) {
123+
Log.i(TAG, "Opened");
114124
for (HubConnectionListener listener : listeners) {
115-
listener.onMessage(hubMessage);
125+
listener.onConnected();
116126
}
127+
send("{\"protocol\":\"json\"}" + SPECIAL_SYMBOL);
128+
}
129+
130+
@Override
131+
public void onMessage(String message) {
132+
Log.i(TAG, message);
133+
SignalRMessage element = gson.fromJson(message.replace(SPECIAL_SYMBOL, ""), SignalRMessage.class);
134+
if (element.getType() == 1) {
135+
HubMessage hubMessage = new HubMessage(element.getInvocationId(), element.getTarget(), element.getArguments());
136+
for (HubConnectionListener listener : listeners) {
137+
listener.onMessage(hubMessage);
138+
}
117139

118-
List<HubEventListener> hubEventListeners = eventListeners.get(hubMessage.getTarget());
119-
if (hubEventListeners != null) {
120-
for (HubEventListener listener : hubEventListeners) {
121-
listener.onEventMessage(hubMessage);
140+
List<HubEventListener> hubEventListeners = eventListeners.get(hubMessage.getTarget());
141+
if (hubEventListeners != null) {
142+
for (HubEventListener listener : hubEventListeners) {
143+
listener.onEventMessage(hubMessage);
144+
}
122145
}
123146
}
124147
}
125-
}
126148

127-
@Override
128-
public void onClose(int code, String reason, boolean remote) {
129-
Log.i(TAG, String.format("Closed. Code: %s, Reason: %s, Remote: %s", code, reason, remote));
130-
for (HubConnectionListener listener : listeners) {
131-
listener.onDisconnected();
149+
@Override
150+
public void onClose(int code, String reason, boolean remote) {
151+
Log.i(TAG, String.format("Closed. Code: %s, Reason: %s, Remote: %s", code, reason, remote));
152+
for (HubConnectionListener listener : listeners) {
153+
listener.onDisconnected();
154+
}
155+
connectionId = null;
132156
}
133-
}
134157

135-
@Override
136-
public void onError(Exception ex) {
137-
Log.i(TAG, "Error " + ex.getMessage());
138-
error(ex);
139-
}
140-
};
158+
@Override
159+
public void onError(Exception ex) {
160+
Log.i(TAG, "Error " + ex.getMessage());
161+
error(ex);
162+
}
163+
};
164+
} catch (Exception e) {
165+
error(e);
166+
}
167+
141168
Log.i(TAG, "Connecting...");
142169
client.connect();
143170
}

0 commit comments

Comments
 (0)