Websocket: vue + node implements real-time communication

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.vueand the chat windowChat/index.vue

3. Write routes

Here I simply added a routing guard

Insert image description here

4. Write a login page

After successful verification, save the name of the logged-in person

Insert image description here

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

Insert image description here

7. Initialize WebSocket

By new WebSocket('ws:localhost:8000'), the backend port I specified here is 8000, it has four events, namely onopen, onmessage, onclose, onerror. Here we mainly use it onmessage. Because the backend returns a Blob to the frontend, I processed it here.

Insert image description here

8. Implement the send button

Insert image description here

Backend part (Node)

1. Initialize project

npm init -y

2. Install dependencies

npm install ws

3. Code writing

Here we mainly use connectionevents, returning a callback with parameters, and the callback parameters listen for messageevents. Real-time communication is completed by server.clientsbroadcasting events.

Insert image description here

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.

Guess you like

Origin blog.csdn.net/weixin_44013288/article/details/126092069