简体   繁体   English

如何更改URL Websocket NodeJ(服务器/客户端)

[英]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 : 我有一个表示为Express的服务器节点Js,我想在同一页面server.js(包含我的所有控制器)中与我的客户端一起使用两个套接字,突然我想将第一个套接字放在url(“ / connection”)下,并且网址(“ / giveUserConnected”)下的第二个网址,将用来代替已连接的用户,例如:

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

To contact server.js : 要联系server.js :

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

and another socket2 in client.html : client.html :另一个socket2 client.html :

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

to contact server.js : 联系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. 您正在将HTTP请求与socket.io请求混合在一起,这是两件事。

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. 当您提供io.connect()的路径名(在本例中为/connection/giveUserConnected )时, socket.io服务器将路径用作客户端连接到的命名空间的名称。

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. listOfUsers是什么取决于您的应用程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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