我想基于URL创建多个名称空间,但我很困惑socket.io

时间:2017-09-08 15:11:49

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

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

server.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);
    });
});

client.js

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

1 个答案:

答案 0 :(得分:1)

server.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>});