What's the difference between these two?
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.
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
.
Why this behavior? How do you know when to use socket.emit
or socket.send
?
Simple and precise (Source: Socket.IO google group):
socket.emit
allows you to emit custom events on the server and clientsocket.send
sends messages which are received with the'message'
eventWith socket.emit you can register custom event like that:
server:
client:
Socket.send does the same, but you don't register to 'news' but to message:
server:
client:
https://socket.io/docs/client-api/#socket-send-args-ack
socket.send
// Sends a message eventsocket.emit(eventName[, ...args][, ack])
// you can custom eventNameTL;DR:
socket.send(data, callback)
is essentially equivalent to callingsocket.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
:and for those keeping score at home, here is what it looks like using
socket.send
:socket.send
is implemented for compatibility with vanilla WebSocket interface.socket.emit
is feature of Socket.IO only. They both do the same, butsocket.emit
is a bit more convenient in handling messages.In basic two way communication systems, socket.emit has proved to be more convincing and easy to use (personal experience) and is a part of Socket.IO which is primarily built for such purposes