websocket(Ⅱ)

spring整合websocket方法

①:配置类,注解扫描

实现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("*");    //有时候连接失败,这里拦截了
}
@Bean
public TextWebSocketHandler chatMessageHandler(){
return new ChatMessageHandler();
}
}

②:实现HandshakeInterceptor接口,握手

@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接口,接收、发送消息

@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

//WebSocketHandler是否处理部分消息。如果此标志设置为true并且底层WebSocket服务器支持部分消息,则可以拆分大型WebSocket消息或未知大小的消息,并且可以通过多次调用接收handleMessage(WebSocketSession, WebSocketMessage)。该标志 WebSocketMessage.isLast()指示消息是否是部分消息以及它是否是最后一部分。
public boolean supportsPartialMessages() {
// TODO Auto-generated method stub
return false;
}

猜你喜欢

转载自www.cnblogs.com/tongCB/p/11281581.html