【问题标题】:io.to(socket.id).emit() not working on cross domainio.to(socket.id).emit() 不能在跨域上工作
【发布时间】:2022-10-17 19:51:47
【问题描述】:
如何使用 specific_room [io.to(socket.id).emit('sendData') ]at 跨域发出事件
这个我试过了
server side
io.emit('sendData', data);
clientside
var socket = io('https://localhost:3000/', { transports: ['websocket'] });
socket.on('sendData', function (data) {
console.log(data);
})
以上语法在跨域上完美运行
但我想在跨域的特定房间发射
io.to(socket.id).emit('sendData', data)
io.broadcast.to(socketid).emit('message', 'for your eyes only'); //sending to individual socketid
参考链接->https://9to5answer.com/cross-domain-connection-in-socket-io
请帮助解决这个问题!
【问题讨论】:
标签:
node.js
sockets
websocket
socket.io
【解决方案1】:
我理解了您的代码,您只需在 socket.io 服务器上发出初始连接
io.on("connection", function(socket){
socket.emit('sendsocketid', data);
})
Cross-domain clientside
var socket = io('https://localhost:3000/', { transports: ['websocket'] });
var obj= [];
socket.on('sendsocketid', function (data) {
console.log(data);
// Now You Can Customize the or add the client Socket .id
var NewSocketid = {
id: socket.id
}
Obj.push(data, NewSocketid)
socket.emit("emitnewSocketId", Obj)
})
socket.on("emitnewSocketId", function(data){
consoleo.log(Obj[1].NewSocketid)
//Now You can emit the new socket id
io.to(Obj[1].NewSocketid).emit('sendData', data)
})