MIT Weblab笔记 - Sockets
Introduction
Steps for a http request:
- Client sends request to Server
- Server responds to client
If we want to achieve a live chat function, where
- A user sends a message
- All users can see the updates message immediately without refreshing the page
However, server cannot send a message without a request. Sockets can solve this!
Sockets
Syntax
- Broadcast a message from server to everyone connected:
1 |
|
- Broadcast a message to a specific client:
1 |
|
- Listen for messages on client:
1 |
|
- The
socketManager
class is defined for demonstration, in real life, please define by yourself.
Usage
1 |
|
1 |
|
What happens in the code:
- When the Chatbook component mounts, it sets up a socket listener for the “message” event using
useEffect
.socket.on("message", addMessages)
adds a listener that calls addMessages whenever a new message is received. When the component unmounts, it calls the return statemnet:socket.off("message", addMessages)
, which cleans up the event listener. - A user sends a POST request to the
/message
endpoint with the chat message content and recipient information. - The backend creates a new message and saves it to the database.
socketManager.getIo().emit("message", message)
: The message is emitted to all connected clients using Socket.io, with data “message”.socket.on("message", addMessages)
listener calls the addMessages function with “message” as parameter, updating the existing messages.
- setActiveChat here can also accept a function as an argument. This function receives the previous state
prevActiveChat
as its argument.
MIT Weblab笔记 - Sockets
https://thiefcat.github.io/2024/07/21/MIT-Weblab/socket/