Table of Contents
Scenario
Background
1. POM dependency
2. WebSocket entrance
3. Interceptor implementation
4. Handler processing class
5. Client connection
Home Web Front-end H5 Tutorial Detailed introduction to spring WebSocket

Detailed introduction to spring WebSocket

Jul 03, 2017 pm 03:18 PM
spring web 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>
Copy after login

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();
    }
}
Copy after login
  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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) {

    }
}
Copy after login

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;
    }
}
Copy after login

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关闭");
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

A new programming paradigm, when Spring Boot meets OpenAI A new programming paradigm, when Spring Boot meets OpenAI Feb 01, 2024 pm 09:18 PM

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.

Use Spring Boot and Spring AI to build generative artificial intelligence applications Use Spring Boot and Spring AI to build generative artificial intelligence applications Apr 28, 2024 am 11:46 AM

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

What are the implementation methods of spring programmatic transactions? What are the implementation methods of spring programmatic transactions? Jan 08, 2024 am 10:23 AM

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.

SSE and WebSocket SSE and WebSocket Apr 17, 2024 pm 02:18 PM

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 transaction isolation level in Spring How to set transaction isolation level in Spring Jan 26, 2024 pm 05:38 PM

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.

How to enable administrative access from the cockpit web UI How to enable administrative access from the cockpit web UI Mar 20, 2024 pm 06:56 PM

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 Annotation Revealed: Analysis of Common Annotations Spring Annotation Revealed: Analysis of Common Annotations Dec 30, 2023 am 11:28 AM

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

what does web mean what does web mean Jan 09, 2024 pm 04:50 PM

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.

See all articles