Node.js creates a simple WebSocket interface and connects the interface in Vue to achieve communication interaction.

Node.js creates a simple WebSocket interface and connects the interface in Vue to achieve communication interaction.

Update time:
2024/01/04 Add a simple example of using the WebSocket interface to connect to the Vue project

1. Why use WebSocket?

The biggest feature of WebSocket is that the server can actively push information to the client, and the client can also actively send information to the server. It is a true two-way equal dialogue and is a type of server push technology.
WebSocket is an API technology for full-duplex communication over a TCP connection. Compared with the traditional HTTP type API, the WebSocket type interface has lower latency and higher efficiency. It is suitable for scenarios that require long-term connection and real-time transmission of data, such as online games, real-time chat and other services.
WebSocket is a long link technology based on HTTP. The traditional HTTP protocol is a request-response model. If the browser does not send a request, the server cannot actively push data to the browser. If you need to push data to the browser regularly, such as stock quotes, or push data to the browser from time to time, such as online chat, to implement such needs based on the HTTP protocol, you can only rely on the browser's JavaScript scheduled polling, which is very inefficient and real-time. Sex is not high.
WebSocket features:
When implementing data push, most of them are ajax polling (at specific time intervals, the browser actively initiates requests, which will occupy a lot of bandwidth and server resources). After WebSocket establishes a TCP connection, the server can actively transfer data to the client, which can better save server resources and bandwidth and achieve more real-time data communication.
Because WebSockets can only send plain text data and binary data over the connection, complex data structures must be JSON.stringify() serialized before being sent over the connection.
The protocol identifier is ws (or wss for encryption), and the server address is the URL. Such as "ws://localhost:8080".

2. Sample code

Simple WebSocket interface

ws is an easy-to-use, extremely fast, and fully tested WebSocket client and server implementation.

npm install ws
const http = require("http");
const WebSocket = require("ws");
const server = http.createServer();
// const WebSocketServer = WebSocket.WebSocketServer;
const socket = new WebSocket.Server({
    
     server });

socket.on("connection", (scoket) => {
    
    
  console.log("连接已打开");
  scoket.on("message", (msg) => {
    
    
    console.log("收到消息==》" + msg);
    scoket.send("返回==》" + msg);
  });
  scoket.on("close", (msg) => {
    
    
    console.log("WebSocket连接已关闭", msg);
  });
});

server.listen(3000, () => {
    
    
  console.log("server start succeed http://127.0.0.1:3000");
});

3. Connect the websocket interface in Vue

Just a simple example for reference only

<script setup>
import {
    
     ref, onMounted } from "vue";

const ws_path = ref("ws://127.0.0.1:3000");
const ws = ref({
    
    });

const connect_ws = () => {
    
    
  ws.value = new WebSocket(ws_path.value);
  //监听是否连接成功
  ws.value.onopen = () => {
    
    
    console.log("ws连接状态:" + ws.value.readyState);
    //连接成功则发送一个数据
    ws.value.send("连接成功");
  };

  //接听服务器发回的信息并处理展示
  ws.value.onmessage = (data) => {
    
    
    console.log("接收到来自服务器的消息:",data);
  };
};

onMounted(() => {
    
    
//   connect_ws();
});
</script>

4. Test the interface connection communication effect

The websocket online test website
can be used whether it is an intranet or an external network. It is just a simple test connection.
The new version of Apifox can also be used to test the websocket interface
WebSocket interface
Test example
Reference content:
MDN WebSocket interface API reference
WebSocket in js
WebSocket tutorial - Ruan Yifeng's network log

Guess you like

Origin blog.csdn.net/yuyunbai0917/article/details/134991484