Below is part of app.js, it has socket connection with client
下面是app.js的一部分,它与客户端有套接字连接
io.sockets.on('connection', function (soc) {
soc.emit('news', { status: 'connected' });
});
What I want to do is access the soc var outside the connection closure, like this
我想要做的是访问连接闭包之外的soc var,就像这样
io.sockets.on('connection', function (soc) {
do something magical here so I can access soc from outside
});
soc.emit('news', { status: 'connected' });
What additional technique need to add in to archive this structure?
需要添加哪些其他技术来存档此结构?
2 个解决方案
#1
4
you need to reference your socket io variable in your server code:
您需要在服务器代码中引用socket io变量:
io.sockets.emit('news', { status: 'connected' });
io.sockets.emit('news',{status:'connected'});
so in your sample code, it could look something like this:
所以在你的示例代码中,它看起来像这样:
io.sockets.on('connection', function (soc) {
emit();
});
function emit(){
io.sockets.emit('news', { status: 'connected' });
}
#2
0
Maybe you could try something like this:
也许你可以尝试这样的事情:
var foo;
io.on('connection', function(soc){
foo = new Foo(soc);
});
function Foo (socket){
this.emit = function () {
if(socket)
{
socket.emit('msg');
}
}
}
After somebody is connected you can call foo.emit();
有人连接后你可以调用foo.emit();
This answer might help you: Can't emit from method defined outside of socket connection
这个答案可能对您有所帮助:无法从套接字连接外定义的方法发出
#1
4
you need to reference your socket io variable in your server code:
您需要在服务器代码中引用socket io变量:
io.sockets.emit('news', { status: 'connected' });
io.sockets.emit('news',{status:'connected'});
so in your sample code, it could look something like this:
所以在你的示例代码中,它看起来像这样:
io.sockets.on('connection', function (soc) {
emit();
});
function emit(){
io.sockets.emit('news', { status: 'connected' });
}
#2
0
Maybe you could try something like this:
也许你可以尝试这样的事情:
var foo;
io.on('connection', function(soc){
foo = new Foo(soc);
});
function Foo (socket){
this.emit = function () {
if(socket)
{
socket.emit('msg');
}
}
}
After somebody is connected you can call foo.emit();
有人连接后你可以调用foo.emit();
This answer might help you: Can't emit from method defined outside of socket connection
这个答案可能对您有所帮助:无法从套接字连接外定义的方法发出