socket. emit - This method is responsible for sending messages. socket. on - This method is responsible for listening for incoming messages.
emit() to send a message to all the connected clients. This code will notify when a user connects to the server. io.on("connection", function(socket) { io.emit(“user connected”); }); If you want to broadcast to everyone except the person who connected you can use. socket.
Simply said Each socket emits its msg to a server(io is an instance of server) and server, in turn, emits it to all connected sockets.
socket. emit() happens to return the socket itself (allows for method chaining). But, that's not relevant here because there's no point in returning any value from a Promise executor function. If you do return a value, it is not used by the Promise in any way.
With socket.emit you can register custom event like that:
server:
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);
});
});
client:
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
Socket.send does the same, but you don't register to 'news' but to message:
server:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.send('hi');
});
client:
var socket = io.connect('http://localhost');
socket.on('message', function (message) {
console.log(message);
});
Simple and precise (Source: Socket.IO google group):
socket.emit
allows you to emit custom events on the server and client
socket.send
sends messages which are received with the 'message'
event
TL;DR:
socket.send(data, callback)
is essentially equivalent to calling socket.emit('message', JSON.stringify(data), callback)
Without looking at the source code, I would assume that the send function is more efficient edit: for sending string messages, at least?
So yeah basically emit allows you to send objects, which is very handy.
Take this example with socket.emit
:
sendMessage: function(type, message) {
socket.emit('message', {
type: type,
message: message
});
}
and for those keeping score at home, here is what it looks like using socket.send
:
sendMessage: function(type, message) {
socket.send(JSON.stringify({
type: type,
message: message
}));
}
socket.send
is implemented for compatibility with vanilla WebSocket interface. socket.emit
is feature of Socket.IO only. They both do the same, but socket.emit
is a bit more convenient in handling messages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With