0


springboot实现websocket服务端搭建,URL带参数连接(超详细)

一、在项目中pom文件引入websocket相关依赖

        <!-- Spring WebSocket -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

二、创建WebSocketInterceptor类

创建WebSocketInterceptor类,实现HandshakeInterceptor接口。

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

public class WebSocketInterceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 从请求中获取查询参数并存入attributes中
        String queryString = request.getURI().getQuery();
        if (queryString != null) {
            String[] queryParams = queryString.split("&");
            for (String queryParam : queryParams) {
                String[] keyValue = queryParam.split("=");
                if (keyValue.length == 2) {
                    attributes.put(keyValue[0], keyValue[1]);
                }
            }
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                               WebSocketHandler wsHandler, Exception ex) {
        // 握手完成后不需要执行任何操作
    }
}

三、创建WebSocketConfig类

创建WebSocketConfig类,实现WebSocketConfigurer接口,注意加入相关注解,否则springboot启动后websocket无法自动运行

@Slf4j
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myWebSocketHandler(), "/websocket").setAllowedOrigins("*")
                .addInterceptors(new WebSocketInterceptor());
    }

    @Bean
    public MyWebSocketHandler myWebSocketHandler() {
        return new MyWebSocketHandler();
    }

}

四、创建MyWebSocketHandler类,实TextWebSocketHandler接口

import cn.hutool.crypto.digest.DigestUtil;
import com.manage.component.socket.entity.KeyServerMessage;
import com.manage.component.security.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

@Slf4j
public class MyWebSocketHandler extends TextWebSocketHandler {
    // 存储连接的客户端 Session
    private static List<WebSocketSession> sessions = new CopyOnWriteArrayList<>(); // 使用并发安全的 List 实现

    public static List<WebSocketSession> getSessions() {
        return sessions;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 获取握手请求中传递的查询参数
        Map<String, Object> attributes = session.getAttributes();
        String type = (String) attributes.get("type");
        String devInfo = (String) attributes.get("devInfo");

        // 在这里处理连接建立后的逻辑,可以使用type和devInfo参数
        System.out.println("WebSocket opened with type: " + type + " and devInfo: " + devInfo);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        // 接收到客户端消息时的处理逻辑
        try {
            String messageText = new String(message.asBytes(), StandardCharsets.UTF_8);
            log.info("接收到客户端消息:" + messageText);
        } catch (UnsupportedCharsetException e) {
            log.error("解析消息时发生异常", e);
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        sessions.remove(session);
        log.info("WebSocket 连接已关闭。关闭状态:" + status);
    }

    // 后台数据发生变化时,通过 WebSocket 推送数据给客户端
    public void pushDataToClients(String data) throws IOException {
        for (WebSocketSession session : sessions) {
            session.sendMessage(new TextMessage(data.getBytes(StandardCharsets.UTF_8))); // 指定字符编码为UTF-8
        }
    }

    // 关闭指定客户端的连接
    public void closeConnection(WebSocketSession session) {
        sessions.remove(session);
        try {
            session.close(); // 主动关闭websocket连接
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @MessageMapping("/app/message") // 定义与客户端发送消息时的目标端点匹配的映射路径
    public void handleMessage(@Payload String message) {
        // 在这里处理接收到的消息
        log.warn("Received message from client: " + message);
    }
}

在上面服务连接中传递了两个参数:type 和 devInfo ,并正常接收,启动springboot,websocket服务自动启动,因为加了注解,无需在启动类中调用。

服务地址为: ws://127.0.0.1:4046/websocket?type=1&devInfo=bbbb ,其中 type的值和devInfo的值可以任意传递,接收成功

2024-05-09 10:11:30 [http-nio-4046-exec-3] DEBUG org.springframework.security.web.FilterChainProxy -/websocket?type=1&devInfo=bbbb has an empty filter list
2024-05-09 10:11:30 [http-nio-4046-exec-3] DEBUG org.springframework.web.servlet.DispatcherServlet -GET "/websocket?type=1&devInfo=bbbb", parameters={masked}
2024-05-09 10:11:30 [http-nio-4046-exec-3] DEBUG org.springframework.web.socket.server.support.WebSocketHandlerMapping -Mapped to org.springframework.web.socket.server.support.WebSocketHttpRequestHandler@6a51ae7c
2024-05-09 10:11:30 [http-nio-4046-exec-3] DEBUG org.springframework.web.socket.server.support.WebSocketHttpRequestHandler -GET /websocket
2024-05-09 10:11:30 [http-nio-4046-exec-3] DEBUG org.springframework.web.servlet.DispatcherServlet -Completed 101 SWITCHING_PROTOCOLS
2024-05-09 10:11:30 [http-nio-4046-exec-3] DEBUG org.springframework.web.socket.handler.LoggingWebSocketHandlerDecorator -New StandardWebSocketSession[id=ddaf2ce8-ca6b-45f5-a540-68b7dd70819a, uri=ws://127.0.0.1:4046/websocket?type=1&devInfo=bbbb]
WebSocket opened with type: 1 and devInfo: bbbb

启动并完美接收,成功!


本文转载自: https://blog.csdn.net/lyy4417/article/details/138600736
版权归原作者 代码精灵 所有, 如有侵权,请联系我们删除。

“springboot实现websocket服务端搭建,URL带参数连接(超详细)”的评论:

还没有评论