路由中带有变量/ id的Socket.io命名空间

时间:2018-04-15 10:52:49

标签: javascript node.js sockets websocket socket.io

我遇到了问题:

我使用会议室加入系统 [我只在NodeJS中编程]和 socket.io

https://example.com/room/:roomid/

e.g。 https://example.com/room/764363553/

我的路线:

router.get('/room/:roomid/', function (req, res, next) {
    var id = req.params.roomid;
    //....
});

我想在房间里制作套接字,但我是如何使用命名空间制作的呢?

io.of("/room/:roomid/").on('connection', function (socket) {
   io.of("/room/:roomid/").emit('testsocket');
}

- >不起作用

客户代码:

var socketIO = io(window.location.pathname);

socketIO.on('testsocket', function (data) {
        console.log("socket successful connected!");
});

2 个答案:

答案 0 :(得分:1)

服务器

var manager = io.of("/room").on('connection', function (socket) {
   socket.on("join", function(roomid){
       socket.join(roomid);
       manager.to(roomid).emit('testsocket',roomid);
   }
}

客户端:

var socketIO = io("/room");
var roomID = window.location.pathname.splitOnLast("/")[1]; //Should ideally be got from req.params.roomid
socketIO.emit("join", roomID)
socketIO.on('testsocket', function (data) {
    console.log("Connected to room", data);
});

答案 1 :(得分:0)

Socketio从2.1.0开始支持动态名称空间。

pr是here

document is here

还可以提供正则表达式或函数,以便以动态方式创建名称空间:

const dynamicNsp = io.of(/^\/dynamic-\d+$/).on('connect', (socket) => {
  const newNamespace = socket.nsp; // newNamespace.name === '/dynamic-101'

  // broadcast to all clients in the given sub-namespace
  newNamespace.emit('hello');
});

// client-side
const socket = io('/dynamic-101');

// broadcast to all clients in each sub-namespace
dynamicNsp.emit('hello');

// use a middleware for each sub-namespace
dynamicNsp.use((socket, next) => { /* ... */ });

具有功能:

io.of((name, query, next) => {
  next(null, checkToken(query.token));
}).on('connect', (socket) => { /* ... */ });