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屋!