Skip to content

Commit 377c6b6

Browse files
committed
Merge pull request TooTallNate#27 from xpepermint/master
WebSocketClient close socket connection issue
2 parents 5900985 + 1087c5e commit 377c6b6

File tree

1 file changed

+24
-9
lines changed

1 file changed

+24
-9
lines changed

src/net/tootallnate/websocket/WebSocketClient.java

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -120,8 +120,22 @@ public void close() throws IOException
120120
{
121121
if (running)
122122
{
123-
selector.wakeup();
124-
conn.close();
123+
// must be called to stop do loop
124+
running = false;
125+
126+
// call this inside IF because it can be null if the connection has't started
127+
// but user is calling close()
128+
if (selector != null && conn != null)
129+
{
130+
selector.wakeup();
131+
conn.close();
132+
// close() is synchronously calling onClose(conn) so we don't have to
133+
}
134+
else
135+
{
136+
// connection has't started but the onClose events should be triggered
137+
onClose(conn);
138+
}
125139
}
126140
}
127141

@@ -164,8 +178,13 @@ private boolean tryToConnect(InetSocketAddress remote) {
164178
selector = Selector.open();
165179

166180
this.conn = new WebSocket(client, new LinkedBlockingQueue<ByteBuffer>(), this);
167-
// At first, we're only interested in the 'CONNECT' keys.
168-
client.register(selector, SelectionKey.OP_CONNECT);
181+
// the client/selector can be null when closing the connection before its start
182+
// so we have to call this part inside IF
183+
if (client != null)
184+
{
185+
// At first, we're only interested in the 'CONNECT' keys.
186+
client.register(selector, SelectionKey.OP_CONNECT);
187+
}
169188

170189
} catch (IOException ex) {
171190
onIOError(conn, ex);
@@ -364,11 +383,7 @@ public void onOpen(WebSocket conn) {
364383
*/
365384
public void onClose(WebSocket conn)
366385
{
367-
if (running)
368-
{
369-
onClose();
370-
}
371-
386+
onClose();
372387
releaseAndInitialize();
373388
}
374389

0 commit comments

Comments
 (0)