Skip to content

Commit 1087c5e

Browse files
author
Kristijan Sedlak
committed
fixing close() connection when has't started error issue (NullPointerException)
1 parent 877314d commit 1087c5e

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

src/net/tootallnate/websocket/WebSocketClient.java

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -120,9 +120,22 @@ public void close() throws IOException
120120
{
121121
if (running)
122122
{
123-
running = false; // must be called to stop do loop
124-
selector.wakeup();
125-
conn.close(); // synchronously calling onClose(conn)
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+
}
126139
}
127140
}
128141

@@ -165,8 +178,13 @@ private boolean tryToConnect(InetSocketAddress remote) {
165178
selector = Selector.open();
166179

167180
this.conn = new WebSocket(client, new LinkedBlockingQueue<ByteBuffer>(), this);
168-
// At first, we're only interested in the 'CONNECT' keys.
169-
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+
}
170188

171189
} catch (IOException ex) {
172190
onIOError(conn, ex);

0 commit comments

Comments
 (0)