Detailed introduction to spring WebSocket
Scenario
Websocket is one of the new features of Html5. The purpose is to establish a full-duplex communication method between the browser and the server to solve the excessive resource consumption caused by http request-response. At the same time, it provides new implementation methods for special scenario applications, such as chat, stock trading, games and other industries that require high real-time performance.
Background
Only one-way communication can be achieved through http in the browser. Comet can simulate two-way communication to a certain extent, but the efficiency is low and a server is required. There is good support; socket and xmlsocket in flash can achieve true two-way communication. Through flex ajax bridge, these two functions can be used in javascript. It is foreseeable that if websocket is once in the browser If implemented, it will replace the above two technologies and be widely used. Faced with this situation, HTML5 defines the WebSocket protocol, which can better save server resources and bandwidth and achieve real-time communication. At present, all major mainstream browsers support websocket, IE browser requires IE10+
1. POM dependency
POM dependency, spring4.1.4.RELEASE, spring Please add core dependencies by yourself. The following are websocket related jar
<dependency> <groupId>javax.websocket</groupId> <artifactId>javax.websocket-api</artifactId> <version>1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-websocket</artifactId> <version>4.1.4.RELEASE</version> </dependency>
2. WebSocket entrance
@Configuration @EnableWebMvc @EnableWebSocket public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { //允许连接的域,只能以http或https开头 String[] allowsOrigins = {"http://www.xxx.com"}; //WebIM WebSocket通道 registry.addHandler(chatWebSocketHandler(),"/ webSocketIMServer").setAllowedOrigins(allowsOrigins).addInterceptors(myInterceptor()); registry.addHandler(chatWebSocketHandler(), "/sockjs/w ebSocketIMServer").setAllowedOrigins(allowsOrigins).addInterceptors(myInterceptor()).withSockJS(); } @Bean public ChatWebSocketHandler chatWebSocketHandler() { return new ChatWebSocketHandler(); } @Bean public WebSocketHandshakeInterceptor myInterceptor(){ return new WebSocketHandshakeInterceptor(); } }
Implement the WebSocketConfigurer interface and override the registerWebSocketHandlers method. This is a core implementation method , configure the websocket entrance, allowed access domains, registered Handler, SockJs support and interceptor.
registry.addHandler registration and routing function, when the client initiates a websocket connection, the /path is handed over to the corresponding handler for processing without implementing specific business logic, which can be understood as collection and task distribution center.
setAllowedOrigins(String[] domains) allows the specified domain name or IP (including port number) to establish a long connection. If you only allow access to your own domain name, you can easily set it here. If the "*" sign is used without time limit, if a domain name is specified, it must start with http or https.
addInterceptors, as the name suggests, is to add interceptors to the handler. We can add our own logic code before and after calling the handler.
spring websocket also supports STOMP protocol, I will share it next time.
3. Interceptor implementation
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor { @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object > attributes) throws Exception { if (request instanceof ServletServerHttpRequest) { attributes.put("username",userName); } return true; } @Override public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) { } }
beforeHandshake, handle the method before calling the handler. Commonly used to register user information, bind WebSocketSession, and obtain WebSocketSession to send messages based on user information in the handler.
4. Handler processing class
public class ChatWebSocketHandler extends TextWebSocketHandler{ private final static List<WebSocketSession> sessions = Collections.synchronizedList(new ArrayList<WebSocketSession>()); //接收文本消息,并发送出去 @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { chatTextMessageHandler(message.getPayload()); super.handleTextMessage(session, message); } //连接建立后处理 @SuppressWarnings("unchecked") @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { logger.debug("connect to the websocket chat success......"); sessions.add(session); //处理离线消息 } //抛出异常时处理 @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { if(session.isOpen()){ session.close(); } logger.debug("websocket chat connection closed......"); sessions.remove(session); } //连接关闭后处理 @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { logger.debug("websocket chat connection closed......"); sessions.remove(session); } @Override public boolean supportsPartialMessages() { return false; } }
5. Client connection
var host = window.location.host; var websocket; if ('WebSocket' in window) { websocket = new ReconnectingWebSocket("ws://" + host + "/webSocketIMServer", null, {debug:true, maxReconnectAttempts:4}); } else if ('MozWebSocket' in window) { websocket = new MozWebSocket("ws://" + host + "/webSocketIMServer"); } else { websocket = new SockJS("http://" + host + "/sockjs/webSocketIMServer"); } websocket.onopen = function(evnt) { console.log("websocket连接上"); }; websocket.onmessage = function(evnt) { messageHandler(evnt.data); }; websocket.onerror = function(evnt) { console.log("websocket错误"); }; websocket.onclose = function(evnt) { console.log("websocket关闭"); }
ReconnectingWebSocket.js is used here, and extensions are added to the browser's own websocket, such as reconnection , connection timeout, failed reconnection interval, maximum number of connection attempts, etc.
Project homepage:ReconnectingWebSocket
The above is the detailed content of Detailed introduction to spring WebSocket. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In 2023, AI technology has become a hot topic and has a huge impact on various industries, especially in the programming field. People are increasingly aware of the importance of AI technology, and the Spring community is no exception. With the continuous advancement of GenAI (General Artificial Intelligence) technology, it has become crucial and urgent to simplify the creation of applications with AI functions. Against this background, "SpringAI" emerged, aiming to simplify the process of developing AI functional applications, making it simple and intuitive and avoiding unnecessary complexity. Through "SpringAI", developers can more easily build applications with AI functions, making them easier to use and operate.

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

How to implement spring programmatic transactions: 1. Use TransactionTemplate; 2. Use TransactionCallback and TransactionCallbackWithoutResult; 3. Use Transactional annotations; 4. Use TransactionTemplate in combination with @Transactional; 5. Customize the transaction manager.

In this article, we will compare Server Sent Events (SSE) and WebSockets, both of which are reliable methods for delivering data. We will analyze them in eight aspects, including communication direction, underlying protocol, security, ease of use, performance, message structure, ease of use, and testing tools. A comparison of these aspects is summarized as follows: Category Server Sent Event (SSE) WebSocket Communication Direction Unidirectional Bidirectional Underlying Protocol HTTP WebSocket Protocol Security Same as HTTP Existing security vulnerabilities Ease of use Setup Simple setup Complex performance Fast message sending speed Affected by message processing and connection management Message structure Plain text or binary Ease of use Widely available Helpful for WebSocket integration

How to set the transaction isolation level in Spring: 1. Use the @Transactional annotation; 2. Set it in the Spring configuration file; 3. Use PlatformTransactionManager; 4. Set it in the Java configuration class. Detailed introduction: 1. Use the @Transactional annotation, add the @Transactional annotation to the class or method that requires transaction management, and set the isolation level in the attribute; 2. In the Spring configuration file, etc.

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit

Spring is an open source framework that provides many annotations to simplify and enhance Java development. This article will explain commonly used Spring annotations in detail and provide specific code examples. @Autowired: Autowired @Autowired annotation can be used to automatically wire beans in the Spring container. When we use the @Autowired annotation where dependencies are required, Spring will find matching beans in the container and automatically inject them. The sample code is as follows: @Auto

The web is a global wide area network, also known as the World Wide Web, which is an application form of the Internet. The Web is an information system based on hypertext and hypermedia, which allows users to browse and obtain information by jumping between different web pages through hyperlinks. The basis of the Web is the Internet, which uses unified and standardized protocols and languages to enable data exchange and information sharing between different computers.
