用户可以通过点击 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/