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注释,反之亦然。

相关推荐
爱宇阳7 分钟前
从容器化到自动化:Spring Boot 项目 Docker 部署与 GitLab CI/CD 集成 Harbor 全流程
spring boot·docker·自动化
用户214118326360228 分钟前
Claude Skills 实战指南:3 分钟搞定 PPT、海报与 Logo,AI 办公效率翻倍!
后端
想搞艺术的程序员43 分钟前
Go Error 全方位解析:原理、实践、扩展与封装
开发语言·后端·golang
程序定小飞2 小时前
基于springboot的web的音乐网站开发与设计
java·前端·数据库·vue.js·spring boot·后端·spring
舒一笑2 小时前
从手写周报到智能生成:PandaCoder如何让你的工作汇报效率提升10倍
后端·程序员·intellij idea
无名之辈J2 小时前
支付常犯错误
后端
武昌库里写JAVA2 小时前
element-ui 2.x 及 vxe-table 2.x 使用 css 定制主题
java·vue.js·spring boot·sql·学习
申阳3 小时前
Day 6:04. 基于Nuxt开发博客项目-LOGO生成以及ICON图标引入
前端·后端·程序员
硅胶人3 小时前
[prowlarr][radarr][sonarr][qBitorrent]套件打造家庭影音中心
后端