websocket(Ⅱ)

spring websocket integration method

①: configuration class, annotations scan

Achieve WebSocketConfigurer

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;
import org.springframework.web.socket.handler.TextWebSocketHandler;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(chatMessageHandler(),"/webSocketServer").addInterceptors(new ChatHandshakeInterceptor());
registry.addHandler(chatMessageHandler(), "/sockjs/webSocketServer").addInterceptors(new ChatHandshakeInterceptor()).withSockJS();

registry.addHandler (socketHandler (), "/ SocketServer") addInterceptors (new ChatIntercepter ()) setAllowedOrigins ( "*");.. // Sometimes the connection fails, there intercepted
}
@Bean
public TextWebSocketHandler chatMessageHandler () {
return new new ChatMessageHandler ();
}
}

②: achieve HandshakeInterceptor interface handshake

@Override

//握手接收器
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws Exception {
// TODO Auto-generated method stub
return false;
}
@Override

//握手后,存用户信息
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Exception exception) {
// TODO Auto-generated method stub
}

③ WebSocketHandler implement the interface, receiving, sending a message

@Override

//建立连接后
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// TODO Auto-generated method stub
}
@Override

//接收消息
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
// TODO Auto-generated method stub
}
@Override

//连接失败
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
// TODO Auto-generated method stub
}
@Override

//关闭连接
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
// TODO Auto-generated method stub
}
@Override

Whether // WebSocketHandler processing part of the message. If this flag is set to true and the bottom support portion WebSocket message server, the message can be split WebSocket large or unknown message size, and can be received by multiple calling handleMessage (WebSocketSession, WebSocketMessage). The flag WebSocketMessage.isLast () indicates whether the message is part of the message and it is the last part.
Boolean supportsPartialMessages public () {
// Generated Method Stub the TODO Auto-
return to false;
}

Guess you like

Origin www.cnblogs.com/tongCB/p/11281581.html