socketio / socket.io-client-java

Full-featured Socket.IO Client Library for Java, which is compatible with Socket.IO v1.0 and later.
https://socketio.github.io/socket.io-client-java/installation.html
Other
5.32k stars 972 forks source link

how to disconnect socket.io client from server properly? #704

Closed o7Ghost closed 2 years ago

o7Ghost commented 2 years ago

Hello I'm fairly new to this so i made a simple program to learn. but it seems like when client disconnects from the server, The java program hangs for a bit before completely exits. I'm just wondering if this is normal? if not, how can i disconnect it properly so the java program immediately exits?

Client code

import io.socket.client.*;

public class ChatClient {

    public static void main(String[] args) throws Exception {

        Socket socket = IO.socket("http://localhost:3000");

        Thread t1 = new Thread(new Runnable() {

          public void run() {
            socket.connect();
          }});  

        t1.start();

        Thread.sleep(5000);
        socket.off();
        socket.disconnect();
        //System.exit(0);
    }
}

Server code

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);

io.on('connection', (socket) => {
    console.log('a user connected');
    socket.on('disconnect', () => {
      console.log('user disconnected');
      socket.disconnect();
    });
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});
darrachequesne commented 2 years ago

Added in the documentation here: https://socketio.github.io/socket.io-client-java/faq.html#How_to_properly_close_a_client

One needs to manually shut down the ThreadPoolExecutor:


Dispatcher dispatcher = new Dispatcher();

OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .dispatcher(dispatcher)
        .readTimeout(1, TimeUnit.MINUTES) // important for HTTP long-polling
        .build();

IO.Options options = new IO.Options();
options.callFactory = okHttpClient;
options.webSocketFactory = okHttpClient;

Socket socket = IO.socket(URI.create("https://example.com"), options);

socket.connect();

// then later

socket.disconnect();
dispatcher.executorService().shutdown();

Please reopen if needed.