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

相关推荐
Miss_Chenzr1 分钟前
Springboot优卖电商系统s7zmj(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
程序员游老板1 分钟前
基于SpringBoot3+vue3的爱心陪诊平台
java·spring boot·毕业设计·软件工程·课程设计·信息与通信
期待のcode3 分钟前
Springboot核心构建插件
java·spring boot·后端
2501_921649499 分钟前
如何获取美股实时行情:Python 量化交易指南
开发语言·后端·python·websocket·金融
Miss_Chenzr23 分钟前
Springboot旅游景区管理系统9fu3n(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·旅游
serendipity_hky1 小时前
【SpringCloud | 第5篇】Seata分布式事务
分布式·后端·spring·spring cloud·seata·openfeign
五阿哥永琪1 小时前
Spring Boot 中自定义线程池的正确使用姿势:定义、注入与最佳实践
spring boot·后端·python
Victor3562 小时前
Netty(16)Netty的零拷贝机制是什么?它如何提高性能?
后端
Victor3562 小时前
Netty(15)Netty的线程模型是什么?它有哪些线程池类型?
后端