socket.emit() 与 socket.send() [英] socket.emit() vs. socket.send()
问题描述
这两者有什么区别?
我注意到如果我在工作程序中从 socket.emit
更改为 socket.send
,服务器无法接收消息,虽然我不明白为什么.
I noticed that if I changed from socket.emit
to socket.send
in a working program, the server failed to receive the message, although I don't understand why.
我还注意到,在我的程序中,如果我从socket.emit
改为socket.send
,服务器会收到一条消息,但它似乎收到了多次.当我使用 console.log()
查看服务器收到的内容时,它显示的内容与我使用 socket.emit
时不同.
I also noticed that in my program if I changed from socket.emit
to socket.send
, the server receives a message, but it seems to receive it multiple times. When I use console.log()
to see what the server received, it shows something different from when I use socket.emit
.
为什么会有这种行为?你怎么知道什么时候使用socket.emit
或socket.send
?
Why this behavior? How do you know when to use socket.emit
or socket.send
?
推荐答案
使用 socket.emit 你可以注册这样的自定义事件:
With socket.emit you can register custom event like that:
服务器:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
客户:
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
Socket.send 做同样的事情,但你不是注册到新闻"而是注册消息:
Socket.send does the same, but you don't register to 'news' but to message:
服务器:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.send('hi');
});
客户:
var socket = io.connect('http://localhost');
socket.on('message', function (message) {
console.log(message);
});
这篇关于socket.emit() 与 socket.send()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!