Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is WebSocket technology?

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "what is WebSocket technology". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is WebSocket technology"?

Before WebSocket specification was put forward, developers basically adopted two polling methods to realize the real-time function: polling and Comet technology.

Polling: polling technology requires the client to periodically send requests to the server at set time intervals, frequently querying whether there are any new data changes. Obviously, this approach can lead to too many unnecessary requests, wasting traffic and server resources.

Comet technology can be divided into long polling and streaming technology. Long polling improves the above polling techniques and reduces useless requests. It sets the expiration time for some data and sends a request to the server only when the data expires; this mechanism is suitable for situations where data changes are not particularly frequent. Streaming technology * * means that the client uses a hidden window to establish a HTTP persistent connection with the server. The server will constantly update the connection status to keep the HTTP persistent connection alive before actively pushing data to the client.

Disadvantages: each request and response of these two technologies waste a certain amount of traffic on the same header information, and the development complexity is also large.

With the introduction of WebSocket by HTML5, Bhand S mode has the real-time communication ability of Cmax S mode. WebSocket connections are essentially TCP connections and do not need to be transmitted with duplicate header data. The workflow of WebSocket: the browser sends a request to the server to establish a WebSocket connection through JavaScript. After the WebSocket connection is established successfully, the client and the server can transmit data through the TCP connection.

The relationship between WebSocket, TCP and HTTP

Like http protocol, WebSocket is a reliable protocol based on TCP. When WebSocket establishes a handshake connection, the data is transmitted through http protocol, but after the connection is established, the real data transmission phase does not need http protocol.

Websocket communication principle

As can be clearly seen from the following figure, it is divided into three stages:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Open the handshake.

Data transmission

Turn off the handshake

The following figure shows what WebSocket's main three-step browser and server side do, respectively.

Advantages and disadvantages of websocket

A) the header information exchanged between the server and the client is very small, only about 2 bytes

B) the client and the server can actively transmit data to each other

C) Websocket is an upgrade of the http protocol, which supports persistent connections and requires only one handshake. Create TCP requests and destroy requests without frequency, reduce the consumption of network bandwidth resources, and save server resources at the same time

Spring boot websocket implementation

Introduce dependency

Org.springframework.boot spring-boot-starter-websocket

Create a WebSocket processor

By extending TextWebSocketHandler or BinaryWebSocketHandler, you can override the specified method. When Spring receives a WebSocket event, it automatically calls the method corresponding to the event.

Package com.ganhuojun.websocket.spring; import org.springframework.stereotype.Component; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.WebSocketMessage; import org.springframework.web.socket.WebSocketSession @ Component public class MySpringWebSocketHandler implements WebSocketHandler {/ * callback triggered after establishing a connection * / @ Override public void afterConnectionEstablished (WebSocketSession webSocketSession) throws Exception {System.out.println ("spring Link" + webSocketSession.getId ()) Callback triggered when a message is received * / @ Override public void handleMessage (WebSocketSession webSocketSession, WebSocketMessage webSocketMessage) throws Exception {} / * callback triggered when an error occurs in the transmission of a message * / @ Override public void handleTransportError (WebSocketSession webSocketSession Throwable throwable) callback triggered after throws Exception {} / * is disconnected * / @ Override public void afterConnectionClosed (WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {} / * whether to process the sharding message * / @ Override public boolean supportsPartialMessages () {return false }}

Configure WebSocket

Add a WebSocket processor to the registry

Package com.ganhuojun.websocket.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry @ Configuration @ EnableWebSocket public class SpringWebSocketConfig implements WebSocketConfigurer {@ Override public void registerWebSocketHandlers (WebSocketHandlerRegistry registry) {/ / spring defaults to an OriginHandshakeInterceptor interceptor / / so setAllowedOrigins is required, otherwise websocket returns 403 registry.addHandler (springWebSocketHandler (), "/ spring/websocket"). SetAllowedOrigins ("*");} @ Bean public MySpringWebSocketHandler springWebSocketHandler () {return new MySpringWebSocketHandler ();}}

The front end can write its own js code. This article directly uses the websocket online debugging tool.

Http://www.websocket-test.com/

The figure below is as follows

Test it according to the front and back end code

Backend log

At this point, I believe you have a deeper understanding of "what is WebSocket technology", might as well come to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report