Socket.io
- Node.js course
- Advanced
- Lesson 43/83
- 5 min
Learn realtime communication with Socket.io.
What is Socket.io?
Socket.io is the most popular real-time communication library for Node.js. It provides two-way data flow between client and server. Chat apps, live notifications and multiplayer games are built with Socket.io.
Socket.io is not built in; you install it with npm install socket.io. On the server you import it with const socketIo = require("socket.io");. Socket.io uses WebSocket underneath, but if WebSocket is unavailable it falls back to long polling automatically. That makes browser compatibility very high. In this group you will learn the server side: socketIo(server), io.on, emit, rooms and namespaces.
Creating io with socketIo(server)
You must attach Socket.io to an HTTP server. First create a server with http.createServer, then obtain an io object with socketIo(server). This object manages all real-time events.
Example: const http = require("http"); const server = http.createServer(); const io = socketIo(server);. After this you listen for connecting clients with io.on("connection", ...). The socketIo(server) call binds the server and the Socket.io layer; the client side uses the Socket.io client library. Without an io object no Socket.io feature works.
Practice Import Socket.io
Import the socket.io module with require. Print "Socket.io ready" with console.log.
Starter code
// Import the socket.io module
// write here
// Print "Socket.io ready"
// write hereSample solution
const socketIo = require("socket.io");
console.log("Socket.io ready");Expected output
Socket.io ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is Socket.io imported?
const socketIo = require("socket.io")- const socketIo = new Socket()
- import socket from "realtime"
- const socketIo = require("socket.io") Correct answer
- const socketIo = require("http")
Explanation: Socket.io is imported with require('socket.io').
2 Complete the socketIo call
const io = socketIo(____);
const io = socketIo(server);
Explanation: socketIo(server) creates the io object.
3 Match each piece to its role
| Term | Meaning |
|---|---|
socketIo |
Library |
http.createServer |
HTTP server |
io |
Socket.io instance |
npm install |
Installs the package |