io.on('connection',...)vs io.sockets.on('connection',...)

Sri*_*ath 31 sockets node.js express mean-stack

我正在使用socket.io和Web应用程序的Mean堆栈.我在3006端口上启动了socket的服务器..

var http = require('http').createServer(app);
http.listen(3006);
var io = require('socket.io').listen(http);
Run Code Online (Sandbox Code Playgroud)

这两个似乎都适用于连接.

io.on('connection', function (socket) {
    console.log('Socket succesfully connected with id: '+socket.id);
});
Run Code Online (Sandbox Code Playgroud)

和...

io.sockets.on('connection', function (socket) {
   console.log('Socket succesfully connected with id: '+socket.id);
});
Run Code Online (Sandbox Code Playgroud)

是什么区别io.onio.sockets.on我应该在第一次连接使用哪一个..?

虽然socket.on npm页面 使用io.on了它为什么工作io.sockets.on

小智 13

默认情况下,Socket.IO客户端连接到的默认命名空间是:/.它由io.sockets或简单地io(docs)识别.

此示例从文档中复制:

// the following two will emit to all the sockets connected to `/`

io.sockets.emit('hi', 'everyone');

io.emit('hi', 'everyone');           // short form
Run Code Online (Sandbox Code Playgroud)

我认为'on'和'emit'是相同的:使用'io.sockets'相当于只使用'io',它只是一个较短的形式.

要命名"套接字"套接字,意味着分配不同的端点或路径(这可能很有用).

从这个问题的答案:

"Socket.io为你完成所有工作,好像它是两个独立的实例,但仍然将信息限制为一个连接,这非常聪明."