Skip to content

Commit 6e08d1f

Browse files
docs: how to properly close a client
Related: - #547 - #704
1 parent f3221a4 commit 6e08d1f

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

src/site/markdown/faq.md

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,8 +172,36 @@ options.callFactory = okHttpClient;
172172
options.webSocketFactory = okHttpClient;
173173

174174
for (int i = 0; i < MAX_CLIENTS; i++) {
175-
Socket socket=IO.socket(URI.create("https://example.com"), options);
175+
Socket socket = IO.socket(URI.create("https://example.com"), options);
176176
}
177177
```
178178

179179
Note: we use `MAX_CLIENTS * 2` because a client in HTTP long-polling mode will have one long-running GET request for receiving data from the server, and will create a POST request for sending data to the server.
180+
181+
## How to properly close a client
182+
183+
Calling `socket.disconnect()` may not be sufficient, because the underlying OkHttp client [creates](https://github.com/square/okhttp/blob/06d38cb795d82d086f13c595a62ce0cbe60904ac/okhttp/src/main/java/okhttp3/Dispatcher.java#L65-L66) a ThreadPoolExecutor that will prevent your Java program from quitting for 60 seconds.
184+
185+
As a workaround, you can manually shut down this ThreadPoolExecutor:
186+
187+
```java
188+
Dispatcher dispatcher = new Dispatcher();
189+
190+
OkHttpClient okHttpClient = new OkHttpClient.Builder()
191+
.dispatcher(dispatcher)
192+
.readTimeout(1, TimeUnit.MINUTES) // important for HTTP long-polling
193+
.build();
194+
195+
IO.Options options = new IO.Options();
196+
options.callFactory = okHttpClient;
197+
options.webSocketFactory = okHttpClient;
198+
199+
Socket socket = IO.socket(URI.create("https://example.com"), options);
200+
201+
socket.connect();
202+
203+
// then later
204+
205+
socket.disconnect();
206+
dispatcher.executorService().shutdown();
207+
```

0 commit comments

Comments
 (0)