Home  >  Article  >  Web Front-end  >  Detailed introduction to spring WebSocket

Detailed introduction to spring WebSocket

零下一度
零下一度Original
2017-07-03 15:18:281759browse

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();
    }
}
  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) {

    }
}

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!

Statement:
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