Socket.io client on node.js only works once

I want to create a new sockei.io-client on the server side (with node.js) every time the server receives the request. But the code below only works once, and then sockei.io-client does not respond. The application does not stop, no errors.

var http = require("http"); http.createServer(function(request, response) { var io = require('socket.io-client'); localSocket = io.connect('http://localhost:9876/'); localSocket.on('connect', function (data) { response.writeHead(200, {"Content-type": "text/plain"}); response.write(data.name); response.end(); localSocket.disconnect(); }); }).listen(8080); 

The Socket.io server (on localhost: 9876) works well - it serves clients with names (which

  data.name 

in the code here).

What's wrong?

UPDATE: I solved the problem: to start several connections for socket.io-client you need to add the connection parameter {'force new connection': true}, for example:

 localSocket = io.connect('http://localhost:9876/', {'force new connection': true}); 

Thanks!

+4
source share
1 answer

For those who found this on google - there is a solution for this:

Socket.disconnect () removes the client (server side). There is no chance that the client will stay in touch :)

force disconnect client from server using socket.io and nodejs

I think you just need to remove the disconnect () line.

0
source

Source: https://habr.com/ru/post/1441796/


All Articles