问题描述
我正在使用和堆栈的Web应用程序。我启动了3006端口的套接字服务器。
I am using socket.io and the Mean stack for a web app. I started the server for socket on 3006 port..
var http = require('http').createServer(app);
http.listen(3006);
var io = require('socket.io').listen(http);
这两个都似乎在连接上工作。
Both of these seem to work on connection.
io.on('connection', function (socket) {
console.log('Socket succesfully connected with id: '+socket.id);
});
和...
io.sockets.on('connection', function (socket) {
console.log('Socket succesfully connected with id: '+socket.id);
});
io.on
和 io.sockets.on
以及在第一次连接时应该使用哪一个??
What is the difference between io.on
and io.sockets.on
and which one should I use on first time connection..?
虽然使用 io.on
为什么在 io.sockets.on
推荐答案
Socket.IO客户端默认连接的默认命名空间是: /
。
它由 io.sockets
或简单的 io
()。
The default namespace that Socket.IO clients connect to by default is: /
.It is identified by io.sockets
or simply io
(docs).
此示例从文档中复制:
This example copied from the documentation:
// the following two will emit to all the sockets connected to `/`
io.sockets.emit('hi', 'everyone');
io.emit('hi', 'everyone'); // short form
我认为on是一样的,因为它是'emit ':使用'io.sockets'仅等于使用'io',它只是一个较短的形式。
I assume it is the same for 'on', as it is for 'emit': using 'io.sockets' is equivalent to using 'io' only, it's just a shorter form.
对于命名空间,您的套接字意味着分配不同的端点或路径(可能很有用)。
To "namespace" your sockets, means assigning different endpoints or paths (which can be useful).
从这个答案中这个SO :
From an answer to this SO question:
Socket.io为您做所有的工作,就好像它是两个单独的实例,但仍然限制信息到一个连接,这是很聪明的。
"Socket.io does all the work for you as if it is two separate instances, but still limits the information to one connection, which is pretty smart."
这篇关于io.on('connection',...)vs io.sockets.on('connection',...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!