In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article introduces the relevant knowledge of "how to achieve WebSocket in Spring Boot". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
What is WebSocket?
WebSocket protocol provides a standardized method to establish a full-duplex, two-way communication channel between the client and the server through a single TCP connection. It is a TCP protocol different from HTTP, but is designed to work on HTTP, uses ports 80 and 443, and allows reuse of existing firewall rules.
The WebSocket protocol is independent based on the TCP protocol. Its only relationship with HTTP is that its handshake is interpreted by the HTTP server as an Upgrade request.
Use "Upgrade: websocket" to switch to the websocket protocol:
GET / spring-websocket-portfolio/portfolio HTTP/1.1Host: localhost:8080Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: Uc9l9TMkWGbHFD2qnFHltg==Sec-WebSocket-Protocol: v10.stomp, v11.stompSec-WebSocket-Version: 13Origin: http://localhost:8080
The websocket server returned "101":
HTTP/1.1 101 Switching Protocols Upgrade: websocketConnection: UpgradeSec-WebSocket-Accept: 1qVdfYHU9hPOl4JYYNXF623Gzn0=Sec-WebSocket-Protocol: v10.stompHTTP vs WebSocket
In HTTP, applications provide a lot of URLs. The client accesses these URLs in a request-response style. The server routes these requests to the appropriate processing according to the URL, method, and request header of the request.
WebSocket initializes the connection using only 1 URL. After that, all messages use the same TCP connection. WebSocket is a low-level protocol that does not specify any semantics for the content of the message. This means that messages cannot be routed or processed unless the client and server agree on message semantics.
The WebSocket client and server can agree on a higher level of message protocol (such as STOMP) through the Sec-WebSocket-Protocol request header of the HTTP handshake request
When do I use WebSocket?
WebSockets can make web pages dynamic and interactive. In many cases, however, the combination of Ajax and HTTP streams or long polling can provide a simple and effective solution.
For example, news, email, and social feeds need to be updated dynamically, but there may be no problem updating them every few minutes. On the other hand, collaboration, gaming and financial applications need to be closer to real-time.
Code example 1. SpringBoot uses native WebSocket1.1 to introduce spring-boot-starter-websocket jar org.springframework.boot spring-boot-starter-websocket 2.6.71.2 to write WebSocketHandler
The WebSocket server is implemented in the following ways:
Implement WebSocketHandler interface to inherit BinaryWebSocketHandler and TextWebSocketHandler classes
Package org.spring.boot.websocket;import java.nio.charset.StandardCharsets;import org.springframework.web.socket.TextMessage;import org.springframework.web.socket.WebSocketSession;import org.springframework.web.socket.handler.TextWebSocketHandler / * websocket processing class: add "server returned:" to the requested information, and then return it to the client * @ author black * * / public class EchoTextWebSocketHandler extends TextWebSocketHandler {@ Override protected void handleTextMessage (WebSocketSession session, TextMessage message) throws Exception {/ / received message String requestMsg = message.getPayload (); System.out.println ("Server received:" + requestMsg) / / Organization response information String responseMsg = "Server returns:" + requestMsg; System.out.println (responseMsg); TextMessage respMsg = new TextMessage (responseMsg.getBytes (StandardCharsets.UTF_8)); / / return to client session.sendMessage (respMsg);}} 1.3 write WebSocket configuration package org.spring.boot.websocket;import org.springframework.context.annotation.Bean Import org.springframework.context.annotation.Configuration;import org.springframework.web.socket.WebSocketHandler;import org.springframework.web.socket.config.annotation.EnableWebSocket;import org.springframework.web.socket.config.annotation.WebSocketConfigurer;import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistration;import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry / * WebSocket configuration class * @ author black * * / @ Configuration@EnableWebSocketpublic class WebSocketConfig implements WebSocketConfigurer {public void registerWebSocketHandlers (WebSocketHandlerRegistry registry) {/ / configure specific WebSocketHandler WebSocketHandlerRegistration registration = registry.addHandler (echoHandler (), "/ echo") for the specified URL; / / registration can configure WebSocketHandler} @ Bean public WebSocketHandler echoHandler () {return new EchoTextWebSocketHandler () }} 1.4 launch class package org.spring.boot.websocket; import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication; / * Spring boot using websocket code example * / @ SpringBootApplicationpublic class SpringBootWebSocketBootstrap {public static void main (String [] args) {SpringApplication.run (SpringBootWebSocketBootstrap.class, args);}}
The default port of the application is 8080 and the embedded container is tomcat.
1.5 Test
Use Postman for WebSocket testing.
Create a new WebSocket request:
Enter "localhost:8080"
Click "Connect", and the following shows:
Expand "Connected to localhost:8080/echo", the specific content is:
# Handshake DetailsRequest URL: http://localhost:8080/echoRequest Method: GETStatus Code: 101 # Request HeadersSec-WebSocket-Version: 13Sec-WebSocket-Key: 1bNYHBOf9wqNuy2WUOYIsQ==Connection: UpgradeUpgrade: websocketSec-WebSocket-Extensions: permessage-deflate;client_max_window_ bitsHost: localhost:8080# Response HeadersUpgrade: websocketConnection: upgradeSec-WebSocket-Accept: uh9IkfewEg11GuuAKnbXmpH+Yqo=Sec-WebSocket-Extensions: permessage-deflate;client_max_window_bits=15Date: Sat, 30 Apr 2022 05:53:23 GMT
Enter "hello, I am black!"
Click [Send]
As can be seen in the picture above, the message is displayed in reverse order.
Finally, click the "Disconnect" button next to url to close the connection:
Validation is complete.
This is the end of the content of "how Spring Boot implements WebSocket". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.