Springboot实现WebSocket通信(二)

本文主要介绍基于Spring封装注解实现WebSocket通信

一、引入依赖

如果项目中已引入了spring-boot-starter-web,在引入spring-boot-starter-websocket时,由于spring-boot-starter-websocket集成有spring-boot-starter-web,因此需要将spring-boot-starter-websocket的spring-boot-starter-web包剔除掉,否则可能会导致依赖冲突。

XML 复制代码
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-websocket</artifactId>
	<exclusions>
		<exclusion>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</exclusion>
	</exclusions>
</dependency>

二、创建WebSocket消息处理器

java 复制代码
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

@Component
@Slf4j
public class MyCustomHandle implements WebSocketHandler {

    //建立连接
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
         log.info("websocket connection established, session id:{}, token:{}", session.getId(),
                 session.getAttributes().get("token"));
    }

    //处理消息
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        //获取消息
        String payload = message.getPayload().toString();
        String token = session.getAttributes().get("token").toString();
        log.info("receive message from client, token:{}, message:{}", token, payload);

    }

    //处理异常
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {

    }
    
    
    //连接关闭后的处理
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {

    }

    //是否支持消息的分片处理
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}

三、创建WebSocket消息拦截器

java 复制代码
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

@Component
@Slf4j
public class WebSocketInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        log.info(">>>>>>>>>>>>握手之前触发,所需进行的处理<<<<<<<<<<<<<");
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        log.info(">>>>>>>>>>>>握手之后触发,所需进行的处理<<<<<<<<<<<<<");
    }
}

四、把上面定义的处理器和拦截器注入到配置类中

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
public class WebSocketConf implements WebSocketConfigurer {
    @Autowired
    private WebSocketInterceptor webSocketInterceptor;
    @Autowired
    private MyCustomHandle handle;
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry
                //注册处理器,在WebSocket握手之后进行处理
                .addHandler(handle, "/spring/ws/server")
                // 添加拦截器,在WebSocket握手之前和之后均可进行拦截
                .addInterceptors(webSocketInterceptor)
                //设置允许跨域
                .setAllowedOrigins("*");
    }
}

五、创建WebSocket专用启动类

主要是添加启用Spring封装的WebSocket的注解

java 复制代码
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.socket.config.annotation.EnableWebSocket;

@SpringBootApplication
@EnableWebSocket
public class WebSocketApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebSocketApplication.class, args);
    }
}

注意:在同一个项目时,@ServerEndpoint和@EnableWebSocket只能启用一个,不能同时并存。使用@ServerEndpoint方式时,需将@ServerEndpoint注释,反之亦然。

相关推荐
Q_Q5110082853 小时前
python+springboot毕业季旅游一站式定制服务系统
java·spring boot·python·django·flask·node.js·旅游
杨杨杨大侠3 小时前
探索 Event 框架实战指南:微服务系统中的事件驱动通信:
java·spring boot·微服务·云原生·架构·系统架构
千里码aicood4 小时前
springboot+vue兼职招聘小程序(源码+文档+调试+基础修改+答疑)
vue.js·spring boot·小程序
会跑的葫芦怪5 小时前
Golang 赋值运算符与短声明 (= 与 :=)使用场景
开发语言·后端·golang
数据知道5 小时前
Go基础:Go语言函数和方法详解
开发语言·后端·golang·go语言
我是华为OD~HR~栗栗呀5 小时前
华为od-前端面经-22届非科班
java·前端·c++·后端·python·华为od·华为
Chan167 小时前
【 设计模式 | 创建型模式 建造者模式 】
java·spring boot·设计模式·java-ee·intellij-idea·建造者模式
yzx9910137 小时前
对比django,flask,opencv三大
人工智能·后端·python·django·flask
汤姆yu7 小时前
2025版基于springboot的校内跑腿管理系统
java·spring boot·后端