简体   繁体   中英

How to disconnect a socket once the socket.emit is done

I am using socket.io-java-client for connecting my java class on the server side to node.js and emit some events.

since I am running this on the server I dont want the socket thread to be running always.

As soon as my emit is done I want to disconnect the socket.

I tried

SocketIO socket=new SocketIO("http://IP:9001");
socket.emit("EVENT", "data");
socket.disconnect();

but this fails because we are closing the socket even before it has sent the message.

Is there any handler for emit success? How can I close the socket after the emit is successful?

After you've sent message to server, server can drop connection from its side. Just on event of receiving specific message it simply can disconnect that client socket.
Or server can additionally send response and client can close him self on receiving this response. But server should secure him self creating timeout in order to close idle clients who did not closed them self.
I recommend to do this operation on server side, and do not ever trust client side with such decisions.

Client can do it additionally after some timeout.
If you use Socket.IO just to send one message and close it after message sent, then there is no point to use Socket.IO as it will have overhead based on handshaking process, and you might consider using just HTTP request in order to send single messages to server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM