I am learning node and socket io. I have been watching tutorials, at first it is good, but then, they start to mix up using socket.on(), socket.emit()
and io.on(), io.emit()
. It seems very confusing. Can anyone clear my concept that where to use io
and where to use socket
in nodejs?
CodePudding user response:
Logically think of io
as the top level socket.io engine manager. If you want to do something at the top level that either creates some sort of resource like a socket
or a new namespace object or sends a message to all existing connections in a namespace, then you use io
.
Once you create a resource like a socket, you then use that object itself to operate on it.
On the server, you use io
when you want to listen for new connections or when you want to broadcast to all connections. There are a few other things you can also do with it.
In the client, you use io
when you want to connect to a server.
You use socket
when you want to communicate with one particular connection as that connection is represented by the socket
object. So, each client connection has a socket
object and you send or receive info to/from that client by using methods on the socket
object.
So, const socket = io.connect(url)
or as a shortcut const socket = io(url)
will connect a client to a server and give you the client-side socket
object.
io.on('connection, socket => { ... })
will listen for an incoming client connection on the server and give you the socket
for that new connection.
socket.emit()
sends a message to the other end of that particular socket (whether on client or server).
io.emit()
on the server sends a messages to all current connected clients (technically all clients connected to the top level io
namespace - there can be other namespaces).