简体   繁体   中英

How to change URL Websocket NodeJs (server/client)

I have a server node Js with express I want to use two socket with my clients in the same page server.js (contains all my controllers), suddenly I want to put the first socket under the url ("/connection"), and A second one under the url ("/giveUserConnected") that will serve me to recupir the connected users, par exemple :

client.html :
var socket = io.connect('http://127.0.0.1:9999/connection');

To contact server.js :

app.get('/connection',function (req,res) {
    io.on('connection', function(socket){
    console.log('a user connected'); 
    });
});

and another socket2 in client.html :

var socket2 = io.connect('http://127.0.0.1:9999/giveUserConnected');

to contact server.js :

app.get('/giveUserConnected',function (req,res) {
    io.on('connection', function(socket){
      // to recuper list of users connected 
    });
});

but it does not work what is the solution , thank's

You are mixing HTTP requests with socket.io requests, which are two different things.

When you provide a path name to io.connect() (in this case, /connection and /giveUserConnected ), the socket.io server uses the path as the name to a namespace that the client connects to.

What I think you want is to just create an event handler for a particular message that will return the list of users. You could use acknowledgement functions for that:

// server
io.on('connection', function(socket) {
  socket.on('giveUserConnected', function(fn) {
    fn(listOfUsers);
  });
});

// client
socket.emit('giveUserConnected', function(users) {
  ...
});

What listOfUsers is depends on your app.

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