2017-09-08 29 views
0

用户可以通过点击localhost:3000/nsp1 来访问像nsp1这样的命名空间,与nsp2相同,我想用输入的名字动态创建它们从文本框中 但现在我试着用下面的代码,使只有一个命名空间,但在服务器命中误差不能得到/我的命名空间我想根据URL制作多个命名空间,但是我很困惑socket.io

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'}); 
+0

你应该看看'rooms' [链接](https://socket.io/docs/ rooms-and-namespaces /)]。 –

+0

同意梵天。像这样的动态事物可能应该是房间,而不是命名空间。 – jfriend00

+0

你会给我它的完整代码,我试过了文档上的代码,但它不起作用@BrahmaDev –

回答

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>}); 
+0

但我需要通过敲击在URL中它的名字,使用户进入一个特定的房间像localhost:3000/room1 然后socket.join(“room1”)我可以使用socket.io来做到这一点,或者我必须做一些代码@Brahma –

+0

你不需要为每个房间单独命名空间。 –

+0

明白了。你需要像expressjs.com这样的东西。 Socket.io不这样做。 –