Socket.io Flashcards
What is socket.io
Socket.IO enables real-time, bidirectional and event-based communication. It creates a persistent connection between client and server
full-duplex communication
Bi-diretional communitcation where the server can initiate communication with the client and vica versa.
Which npm library allows us to work with socket.io
npm i socket.io
How to add socket.io to the a client?
In the html file add the following scripts to the body:
then in the public directory create a chat.js file with the following:
io();
How to setup the server to work with sockets?
- setup an express server
const app = express();
- Manually create an http server outside of express
const server = http.createServer(app);
- Pass the raw http server into socket.io
const io = socketio(server);
Difference between io.emit, socket.broadcast.emit and socket.emit?
socket.emit emits an event to a single connection, while io emits an event to every single connection. broadcast.emit sends a message to all connections except for the one that triggers it.