javascript - 我想根据 URL 创建多个命名空间,但我对 socket.io 感到困惑

标签 javascript node.js websocket socket.io namespaces

用户可以通过点击 localhost:3000/nsp1 来访问像 nsp1 这样的命名空间 与 nsp2 相同,我想使用从文本框中输入的名称动态创建它们 但现在我尝试使用下面的代码只创建一个命名空间,但服务器遇到错误 Cannot GET/my-namespace

服务器.js

var io  = require('socket.io')(http, { path: '/my-namespace'});

io
.of('/my-namespace')
.on('connection', function(socket){
    console.log('a user connected with id %s', socket.id);

    socket.on('my-message', function (data) {
        io.of('my-namespace').emit('my-message', data);
        // or socket.emit(...)
        console.log('broadcasting my-message', data);
    });
});

客户端.js

   var socket = io('localhost:3000/my-namespace', { path: '/my-namespace'});

最佳答案

服务器.js

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(3000);
app.get("/contact.html", function (req, res) {
    res.sendfile(__dirname + '/contact.html');
});
app.get("/login.html", function (req, res) {
    res.sendfile(__dirname + '/login.html');
});
app.get("/", function (req, res) {
    res.sendfile(__dirname + '/home.html');
});
app.get(/(^\/[a-zA-Z0-9\-]+$)/, function (req, res) {
    //Matches anything with alphabets,numbers and hyphen without trailing slash
    res.sendfile(__dirname + '/room.html');
});

io.on('connection', function(socket){
    console.log('a user connected with id %s', socket.id);

    socket.on('join', function (room) {
        //May be do some authorization
        socket.join(room);
        console.log(socket.id, "joined", room);
    });
    socket.on('leave', function (room) {
        //May be do some authorization
        socket.leave(room);
        console.log(socket.id, "left", room);
    });
    socket.on('chat message', function (data) {
        //May be do some authorization
        io.to(data.room).emit("chat message", data.message);
    });
});

room.html/client.js

var socket = io('localhost:3000');
socket.emit("join",location.pathname);
socket.emit("chat message",{room:location.pathname, message:<val>});

关于javascript - 我想根据 URL 创建多个命名空间,但我对 socket.io 感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46119596/

相关文章:

node.js - Nodejs 与 PM2 和 Winston 合并日志

node.js - Express URL 参数功能不会将加号 (+) 解码为空格

html - 现代 Web 应用程序的离线和套接字选项有哪些?

javascript - 在没有公共(public) API 的情况下连接到网站 webosocket

ajax - 在 WebSockets 之前,实时浏览器聊天是如何实现的?

带有边缘类型错误 : Cannot read property 'start' of null 的 Javascript Selenium Webdriver

javascript - iframe 的问题

javascript - 如何在本地运行 angularjs Material 文档

node.js - 我无法在 ubuntu 20.04 中安装 Nestjs

javascript - 如何从 jquery 中的字符串中删除第一个字符?