Socket.io
Table of Content
#Introduction
Socket.IO is a library that enables real-time, bidirectional and event-based communication between the browser and the serve
Before socket.io
Pre-socketio
- Built on top of web sockets api
- it has fail over mechanisms, in case it doesnt use web sockets
- Uses tcp
Events
Ping
Pong
emit
on
connect
Namespaces
.of('namespacename')
specifies a namespace name.io.of('/').emit('message')
is shorthandio.emit('message')
io.of('/').on('message')
is shorthandio.on('message')
- on client we use
io('http://localhost:9000/namespacename')
to connect to a namespace
ALL these are server only
Send an event from the server to this socket only:
socket.emit()
socket.send()
Send an event from a socket to a room:
NOTE: remember, this will not go to the sending socket
socket.to(roomName).emit()
socket.in(roomName).emit()
Because each socket has it's own room, named by it's socket.id, a socket can send a message to another socket:
socket.to(anotherSocketId).emit('hey');
socket.in(anotherSocketId).emit('hey');
A namespace can send a message to any room:
io.of(aNamespace).to(roomName).emit()
io.of(aNamespace).in(roomName).emit()
A namespace can send a message to the entire namespace
io.emit()
io.of('/').emit()
io.of('/admin').emit()