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

相关推荐
bcbnb8 小时前
Socket 抓包工具与实战,从抓取到定位(Socket 的命令、分析)
后端
用户8356290780518 小时前
用Python轻松转换Excel表格为HTML格式
后端·python
用户084059812908 小时前
高版本的jdk在使用maven时,如何编译成低版本的class
后端
摇滚侠8 小时前
Spring Boot 3零基础教程,整合Redis,笔记12
spring boot·redis·笔记
荣淘淘8 小时前
互联网大厂Java求职面试全景实战解析(涵盖Spring Boot、微服务及云原生技术)
java·spring boot·redis·jwt·cloud native·microservices·interview
吃饭最爱8 小时前
spring高级知识概览
spring boot
这里有鱼汤8 小时前
炒股的尽头真的是玄学?我用八字+AI做了个实验,结果震惊
后端
hrrrrb8 小时前
【Spring Security】认证(二)
java·后端·spring
程序员爱钓鱼8 小时前
Python编程实战 · 基础入门篇 | Python的版本与安装
后端·python