When it comes to communication, I generally think of two methods: polling and WebSocket.
Polling actually means repeatedly making interface requests to the backend within the same time interval.
The following mainly talks about the implementation of WebSocket and simply implements a chat room.
1. Related technologies used in the case
1. Front-end
used hereQuicklyCompatible with browserWebSocket.
Note: Some browsers are not compatible with WebSocket
2. Backend
This is usingNode
2. Demo implementation
Front-end part (Vite)
1. Initialize project
npm init vue@latest
(Let’s check routing—router)
2. Let’s make two pages
They are the login page
Login/index.vue
and the chat windowChat/index.vue
3. Write routes
Here I simply added a routing guard
4. Write a login page
After successful verification, save the name of the logged-in person
6. Writing of chat page
First of all, we have two variables to store the information entered by the user and the message returned to us by the background. We store them in an array for our convenience.ul>lirendering
7. Initialize WebSocket
By
new WebSocket('ws:localhost:8000')
, the backend port I specified here is8000
, it has four events, namelyonopen
,onmessage
,onclose
,onerror
. Here we mainly use itonmessage
. Because the backend returns a Blob to the frontend, I processed it here.
8. Implement the send button
Backend part (Node)
1. Initialize project
npm init -y
2. Install dependencies
npm install ws
3. Code writing
Here we mainly use
connection
events, returning a callback with parameters, and the callback parameters listen formessage
events. Real-time communication is completed byserver.clients
broadcasting events.
Summarize
WebSocket is a must for every front-end developer. In the past, I would use polling when encountering such problems. But polling has its own shortcomings, which I won’t go into details here. I hope I can get better and better, and I hope the notes I wrote can solve your urgent needs.