WebSocket Principle
WebSocket is a network communication protocol designed to exchange data between clients and servers through a single, persistent connection.
It works as follows:
- Agreement Handshake: The WebSocket protocol is based on the HTTP protocol. The client first sends a WebSocket handshake request (Upgrade request of the HTTP protocol) to the server through an HTTP request. If the server supports WebSocket, it will return a 101 response, indicating that the protocol has been switched to WebSocket.
- Connection establishment: Once the handshake is completed, the client and the server will establish a full-duplex (two-way) communication connection, and the client and the server can send data to each other at any time without re-establishing the connection.
- Data transmission: WebSocket allows clients and servers to send messages at any time. Data transmission is frame-based (each packet is a frame), and the data format of the frame is binary or text.
- Connection closes: When the communication is over, either party can initiate a connection closing request to close the WebSocket connection.
Unlike the traditional HTTP request-response mode, WebSocket provides the advantages of low latency, real-time, and two-way communication, and is especially suitable for applications that require instant data transmission, such as real-time chat, online games, stock markets, etc.
Sample code
1. Java server (using Spring Boot + WebSocket)
On the Java server, we can use Spring Boot and Spring WebSocket to implement WebSocket services.
Step 1: Add dependencies
First, make sure yoursThere are the following dependencies in the file:
<dependencies> <!-- Spring Boot WebSocket support --> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <!-- Spring Boot Web 相关support --> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
Step 2: Create a WebSocket configuration class
import ; import ; import ; import ; import ; @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { // Set application prefix (destination for messaging) ("/topic"); // Set the target prefix for message sending ("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { // Set WebSocket endpoint ("/ws").withSockJS(); } }
Step 3: Create a message processor
import ; import ; import ; @Controller public class WebSocketController { private final SimpMessagingTemplate messagingTemplate; public WebSocketController(SimpMessagingTemplate messagingTemplate) { = messagingTemplate; } @MessageMapping("/chat") public void sendMessage(String message) { // Send a message to /topic/chat ("/topic/chat", message); } }
("/topic/chat", message); } }
Step 4: Launch the Spring Boot application
Create a startup class and run the application:
import ; import ; @SpringBootApplication public class WebSocketApplication { public static void main(String[] args) { (, args); } }
2. Vue client (using Vue + WebSocket)
In the Vue client, we can use the native WebSocket API or use libraries (e.g.sockjs-client
) to simplify the processing.
Step 1: Install dependencies
In the Vue project, we first install itsockjs-client
andstompjs
Library:
npm install sockjs-client stompjs --save
Step 2: Create a WebSocket Service
Create a Vue file and use WebSocket to connect to the backend:
import SockJS from 'sockjs-client'; import Stomp from 'stompjs'; export default { data() { return { stompClient: null, message: '' }; }, mounted() { (); }, methods: { connect() { const socket = new SockJS('http://localhost:8080/ws'); = (socket); ({}, frame => { ('Connected: ' + frame); // Subscribe to messages ('/topic/chat', (messageOutput) => { = ; }); }); }, sendMessage() { ("/app/chat", {}, "Hello, WebSocket!"); } } };
Step 3: Show the message
Display the received message in the template and provide a button to send the message:
<template> <div> <div> <h2>Received Message: {{ message }}</h2> </div> <button @click="sendMessage">Send Message</button> </div> </template> <script> export default { data() { return { message: '' }; }, methods: { sendMessage() { this.$emit('sendMessage', 'Hello Server'); } } } </script>
Step 4: Run the client
Make sure your Vue app can communicate with the backend service, launch the Vue app and check the output of the browser console.
Summarize
- WebSocket Principle: WebSocket is a full duplex protocol. After establishing a connection, data can be exchanged between the client and the server in real time and in two-way. It is based on the HTTP protocol upgrade mechanism. Through a handshake process, the client establishes a WebSocket connection with the server, and subsequent communications do not require re-establishment of the connection.
-
Java Server: Spring Boot provides built-in support for WebSocket, we use
@MessageMapping
Annotation to process messages sent by the client, usingSimpMessagingTemplate
To push messages to the subscribed client. -
Vue Client: Used by Vue client
SockJS
andto implement WebSocket connection and be able to receive messages pushed by the server. The user can send a message through the button, and the server broadcasts it after receiving the message.
The above is personal experience. I hope you can give you a reference and I hope you can support me more.