Websocket实现方式一

创建Websocket处理器继承AbstractWebSocketHandler

  • 覆写public void afterConnectionEstablished(WebSocketSession session)方法,建立Websocket连接
  • 覆写protected void handleTextMessage(WebSocketSession session, TextMessage message)方法,处理接收的消息
  • 发送消息方法webSocketSession.getWebSocketSession().sendMessage(new TextMessage(msg));
  • 覆写异常处理方法public void handleTransportError(WebSocketSession session, Throwable exception)
  • 覆写websocket关闭方法public void afterConnectionClosed(WebSocketSession session, CloseStatus status)
java 复制代码
@Slf4j
@Component
public class MyWsHandler extends AbstractWebSocketHandler {
    private static final Map<String, Session> sessionMap ;//websocket连接集合
    static {
        //初始化
        sessionMap = new ConcurrentHashMap<>();
    }

    /**
     * 建立连接
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        sessionMap.put(session.getId(),session);
        log.info(session.getClientId()+"建立了连接");
    }

    /**
     * 接收消息并处理
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        log.info(sessionBeanMap.get(session.getId()).getClientId()+":"+message.getPayload());
        String param = message.getPayload();//接收到的消息
        sendMessageToOne(session.getId(),param);//发送消息
    }

    /**
     * 传输异常
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
        if(session.isOpen()){
            session.close();
        }
        sessionMap.remove(session.getId());
    }

    /**
     * 连接关闭
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        int clientId = sessionMap.get(session.getId()).getClientId();
        sessionMap.remove(session);
        log.info(clientId+"关闭了连接");
        super.afterConnectionClosed(session, status);
    }
    /**
     * 给指定用户窗口推送消息
     * @param userId
     * @param param
     */
    public void sendMessageToOne(String userId,String param){
        try {
                sessionMap.get(userId).sendMessage(new TextMessage("Hello World!"));
            } catch (IOException | ExecutionException | InterruptedException e) {
                e.printStackTrace();
            }
    }
}

创建Websocket拦截器继承HttpSessionHandshakeInterceptor(非必须)

  • 建立连接前做处理,覆写public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes)
  • 建立连接后做处理,覆写public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex)
java 复制代码
@Component
@Slf4j
public class MyInterceptor extends HttpSessionHandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
       log.info(request.getRemoteAddress().toString()+"开始握手");
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
        log.info(request.getRemoteAddress().toString()+"完成握手");
        super.afterHandshake(request, response, wsHandler, ex);
    }
}

注册Websocket处理器和Websocket拦截器

java 复制代码
@Configuration
@EnableWebSocket
public class MyWsConfig implements WebSocketConfigurer {
    @Resource
    private MyWsHandler myWsHandler;
    @Resource
    private MyInterceptor myWsInterceptor;

    /**
     * 注册,websocket访问路径/myWebsocket
     * @param registry
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myWsHandler,"/myWebsocket").addInterceptors(myWsInterceptor).setAllowedOrigins("*");
    }
}
相关推荐
湖南罗泽南2 小时前
p2p网络介绍
网络·网络协议·p2p
heilai43 小时前
workerman的安装与使用
c++·websocket·http·php·phpstorm·visual studio code
有梦想的咕噜3 小时前
Secure Shell(SSH) 是一种网络协议
运维·网络协议·ssh
wclass-zhengge12 小时前
Netty篇(WebSocket)
网络·websocket·网络协议
CDialog15 小时前
aws申请ssl证书的方法【该证书仅供aws】
服务器·网络协议·ssl
猛男敲代码15 小时前
SSE与WebSocket与MQTT
前端·javascript·websocket
程序员小羊!15 小时前
HTTP&Tomcat&Servle之HTTP详解
网络协议·http·tomcat
Peter_chq15 小时前
【计算机网络】网络框架
linux·c语言·开发语言·网络·c++·后端·网络协议
hgdlip17 小时前
本地连接IP地址的自主设置指南‌
网络·网络协议·tcp/ip·本地连接
好看资源平台17 小时前
Python网络爬虫与数据采集实战——网络协议与HTTP
爬虫·python·网络协议