🕵️ Reading | Changsha ⭐ Software Engineering ⭐ Bachelor’s Degree
🏠 Work | Guangzhou ⭐ Java Full Stack Developer
🌳 Multiple technical forum expert bloggers, over 110,000 fans online
✈️ Official Account | Country Boy Programming. Reply with Java full video tutorial or front-end full video tutorial to get 300G+ tutorial materials and project practical cases
There is a surprise at the bottom of the article!!!✅ 1. What is WebSocket?
WebSocket is a protocol forfull-duplex communication over a single TCP connection.
It establishes a persistent connection through a “protocol upgrade” on top of the traditional HTTP protocol, allowing the client and server to actively send data to each other, no longer limited to the request-response model.
The WebSocket protocol is defined by the IETF (RFC 6455) and the WebSocket API is standardized by the W3C.
✅ 2. WebSocket Communication Mechanism
🔹 1. Establishing Connection (Handshake)
-
The initial connection is established through an HTTP request;
-
The client sends the
<span><span>Upgrade: websocket</span></span>request header; -
The server returns
<span><span>101 Switching Protocols</span></span>indicating that the protocol upgrade was successful.
🔹 2. Bidirectional Communication
-
After the handshake is successful, both the client and server can actively send messages;
-
Messages are transmitted in the form of “frames”, supporting text and binary formats.
🔹 3. Maintaining Connection
-
The connection is a persistent connection;
-
Supports a heartbeat mechanism (Ping/Pong frames) to maintain activity.
Summary of Features
-
Lightweight: Based on the Java-WebSocket library, suitable for client, desktop applications, or intermediate service calls.
-
Event-Driven: Based on callback handling, naturally suitable for asynchronous message models.
-
Supports SSL, proxies, and custom headers: Adaptable to complex deployment environments.
-
Applicable Scenarios: Online monitoring, chat, push clients, crawlers, and real-time data reception.
✅ 3. Differences Between WebSocket and HTTP
| Comparison Dimension |
HTTP Communication |
WebSocket Communication |
| Protocol | Request/Response protocol based on TCP (stateless) | Full-duplex protocol based on TCP |
| Connection Method | Client requests once, server responds once | Establishes a persistent connection with one handshake, allowing bidirectional communication thereafter |
| Status Management | Stateless (client needs to pass identity) | Stateful connection (can maintain session in memory) |
| Data Transmission | Each communication requires the full HTTP header | Small data frames, high transmission efficiency |
| Server Push | Not supported (requires polling or long polling) | Natively supports server push |
| Performance | High connection overhead, high latency | Strong real-time performance, low resource consumption |
| Application Layer Protocol | Explicit: HTTP/1.1, HTTP/2 | After protocol upgrade, it is WS or WSS (encrypted) |
✅ 4. Usage Scenarios for Each
🔹 Scenarios More Suitable for HTTP:
-
Regular request/response, such as page loading, form submission, file uploads, etc.;
-
RESTful API services;
-
Business systems with low-frequency interactions or infrequent data changes.
🔹 Scenarios More Suitable for WebSocket:
-
Real-time systems, such as IM chat, online games, collaborative office, stock market push;
-
Business scenarios where the server needs to actively push messages;
-
High concurrency and low latency communication scenarios (e.g., issuing commands to IoT devices).
✅ 5. How to Choose Between WebSocket and HTTP?
-
Is there a need for real-time communication between front-end and back-end?
-
If yes: WebSocket is more suitable.
-
Is the data transmission frequency high?
-
High-frequency push: WebSocket.
-
Is bidirectional communication needed?
-
For real-time feedback or control (e.g., IoT, IM): WebSocket.
-
Is there a need for the server to actively send messages?
-
If yes: WebSocket.
✅ 6. WebSocket Usage Example (Based on Java + Spring Boot) 1. Introduce dependencies
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId></dependency>
2. Create WebSocket Configuration Class
@Configuration@EnableWebSocketpublic class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(new MyWebSocketHandler(), "/ws") .setAllowedOrigins("*"); // Allow cross-origin }}
3. Write Handler Logic
public class MyWebSocketHandler extends TextWebSocketHandler { private static final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>(); @Override public void afterConnectionEstablished(WebSocketSession session) { String userId = Objects.requireNonNull(session.getUri()).getQuery(); // Can get user ID from parameters sessions.put(userId, session); System.out.println("Connection established: " + userId); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException { System.out.println("Received message: " + message.getPayload()); session.sendMessage(new TextMessage("Received: " + message.getPayload())); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) { sessions.values().remove(session); System.out.println("Connection closed"); } public void sendToUser(String userId, String msg) throws IOException { WebSocketSession session = sessions.get(userId); if (session != null && session.isOpen()) { session.sendMessage(new TextMessage(msg)); } }}
4. Client Code (HTML Example)Java code can also be used to establish the connection
<script> const socket = new WebSocket("ws://localhost:8080/ws?userId=zheng"); socket.onopen = function() { console.log("Connection successful"); socket.send("Hello, server"); }; socket.onmessage = function(event) { console.log("Received message: " + event.data); }; socket.onclose = function() { console.log("Connection closed"); };</script>
5. Java as ClientMaven Dependency
<dependency> <groupId>org.java-websocket</groupId> <artifactId>Java-WebSocket</artifactId> <version>1.5.3</version></dependency>
Code Example: Basic Connection Demo
import org.java_websocket.client.WebSocketClient;import org.java_websocket.handshake.ServerHandshake;import java.net.URI;public class MyWebSocketClient extends WebSocketClient { public MyWebSocketClient(URI serverUri) { super(serverUri); } @Override public void onOpen(ServerHandshake handshakedata) { System.out.println("Connection successful"); send("Hello, server!"); } @Override public void onMessage(String message) { System.out.println("Received message: " + message); } @Override public void onClose(int code, String reason, boolean remote) { System.out.println("Connection closed, code=" + code + ", reason=" + reason + ", remote=" + remote); } @Override public void onError(Exception ex) { System.err.println("Error occurred: " + ex.getMessage()); } public static void main(String[] args) throws Exception { URI serverUri = new URI("ws://localhost:8080/ws?userId=123"); MyWebSocketClient client = new MyWebSocketClient(serverUri); client.connect(); }}
Core Class Description
| Class / Method | Description |
| WebSocketClient | Abstract class that encapsulates WebSocket protocol handling logic, requires a custom subclass to implement event responses. |
| onOpen(ServerHandshake) | Triggered when the connection is successfully established, can send authentication information or initialization commands. |
| onMessage(String message) | Receives messages from the server (text), one of the main business logic entry points. |
| onClose(int code, String reason, boolean remote) | Callback when the connection is closed, can be used for resource cleanup or automatic reconnection. |
| onError(Exception ex) | Triggered when a network or protocol error occurs. |
| connect() | Initiates a connection operation (asynchronously), will automatically trigger onOpen and other events. |
| send(String message) | Sends a message to the server. Also supports send(ByteBuffer) to send binary data. |
Reply with the following content on the official account to obtain the corresponding materials
For example:【Have guided over 100 students to successfully graduate and obtain their diplomas~】
Number 1, indicates obtaining back-end development learning materials
Number 2, indicates obtaining front-end development learning materials
Number 3, indicates obtaining intermediate designer materials for software exams
Number 4, indicates obtaining commonly used online free learning materials for back-end
Number 5, excellent thesis template for computer graduation design
Number 6, source code for front-end and back-end separation project cases
Number 7, source code for SSM project cases
Number 8, source code for all video carousel cases
Number 9, source code for mall system project with front-end and back-end separation
Number 10: source code for mall system front-end and back-end separation project【Graduation Design System】
Number 11: PPT template case for graduation thesis defense
Number 12: system deployment + thesis guidance + topic guidance + development guidance
Number 13: Document summarizing questions for defense
Number 14: Detailed explanation of front-end and back-end project structure modules (understandable for beginners)
More…