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

相关推荐
稚辉君.MCA_P8_Java31 分钟前
Gemini永久会员 containerd部署java项目 kubernetes集群
后端·spring cloud·云原生·容器·kubernetes
yihuiComeOn1 小时前
[源码系列:手写Spring] AOP第二节:JDK动态代理 - 当AOP遇见动态代理的浪漫邂逅
java·后端·spring
e***71672 小时前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
程序猿小蒜2 小时前
基于springboot的的学生干部管理系统开发与设计
java·前端·spring boot·后端·spring
q***56382 小时前
Spring容器初始化扩展点:ApplicationContextInitializer
java·后端·spring
菜鸟‍3 小时前
【后端学习】MySQL数据库
数据库·后端·学习·mysql
Codebee3 小时前
30 分钟落地全栈交互:OneCode CLI+SVG 排课表实战
后端
努力发光的程序员4 小时前
互联网大厂Java面试:从Spring Boot到微服务架构
spring boot·缓存·微服务·消息队列·rabbitmq·spring security·安全框架
TechTrek4 小时前
Spring Boot 4.0正式发布了
java·spring boot·后端·spring boot 4.0
飞梦工作室4 小时前
企业级 Spring Boot 邮件系统开发指南:从基础到高可用架构设计
java·spring boot·后端