java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot中使用原生WebSocket

SpringBoot中使用原生WebSocket详解

作者:Drl2024

文章介绍了如何在SpringBoot中集成原生WebSocket,包括添加依赖、配置WebSocket、创建WebSocket处理器以及处理文本和二进制消息,还提到如何通过URL路径或查询参数传递数据,并展示了如何在后端获取这些参数

SpringBoot中使用原生WebSocket

在Spring Boot中使用原生WebSocket(不使用STOMP协议)可以简化一些场景下的实现,尤其是在不需要消息代理或复杂的消息格式时。

下面是集成原生WebSocket到Spring Boot项目中的步骤:

添加依赖

确保你的pom.xml文件中包含了WebSocket的支持。

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

配置WebSocket

创建一个配置类来启用WebSocket支持并注册端点。

import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // 注册WebSocket处理器,并设置跨域访问
        registry.addHandler(myWebSocketHandler(), "/ws").setAllowedOrigins("*");
    }

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

创建WebSocket处理器

定义一个处理器来处理WebSocket连接、接收消息和关闭连接等事件。

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;

public class MyWebSocketHandler extends TextWebSocketHandler {

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 当建立连接后调用
        System.out.println("Connection established: " + session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 收到文本消息时调用
        String payload = message.getPayload();
        System.out.println("Received message: " + payload);

        // 回应客户端
        session.sendMessage(new TextMessage("Echo: " + payload));
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 连接关闭后调用
        System.out.println("Connection closed: " + session);
    }
}

前端代码示例 (JavaScript)

前端可以通过JavaScript直接与WebSocket服务器交互,无需额外的库。

<!DOCTYPE html>
<html>
<head>
    <title>Native WebSocket Example</title>
</head>
<body>
    <input type="text" id="message"/>
    <button onclick="sendMessage()">Send</button>
    <ul id="messages"></ul>

    <script type="text/javascript">
        var ws = null;

        function connect() {
            // 连接到WebSocket服务器
            ws = new WebSocket('ws://localhost:8080/ws');

            ws.onopen = function() {
                console.log('Connected to server');
            };

            ws.onmessage = function(event) {
                // 接收到服务器的消息时调用
                var messages = document.getElementById('messages');
                var messageElement = document.createElement('li');
                messageElement.textContent = event.data;
                messages.appendChild(messageElement);
            };

            ws.onclose = function() {
                console.log('Disconnected from server');
            };
        }

        function sendMessage() {
            var messageContent = document.getElementById('message').value;
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(messageContent);
            }
        }

        window.onload = connect; // 页面加载完成后连接
    </script>
</body>
</html>

这段代码展示了如何使用原生的WebSocket API建立连接、发送消息以及接收来自服务器的消息。这里没有使用SockJS或STOMP,更适合于简单的双向通信场景。

以上就是Spring Boot中集成原生WebSocket的基本过程。根据你的需求,你可能还需要添加更多功能,比如身份验证、错误处理等。此外,请注意设置合适的跨域策略,以确保WebSocket的安全性。

如何通过MyWebSocketHandler接受前端传过来的参数处理文本或二进制消息?

直接使用WebSocketHandler

不使用STOMP协议,直接使用WebSocketHandler,可以通过覆盖handleTextMessage方法来处理从客户端发送来的消息。在这个方法中,可以解析消息内容并提取出参数。

后端代码示例(Java)

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;

public class MyWebSocketHandler extends TextWebSocketHandler {

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 解析消息内容
        String payload = message.getPayload();
        // 这里可以将payload转换为JSON对象,然后获取参数
        // 假设我们有一个工具类JsonUtil可以进行JSON解析
        Map<String, Object> params = JsonUtil.parse(payload, Map.class);

        // 根据参数做相应的处理...
        // 如果需要响应客户端,可以使用session.sendMessage(new TextMessage(response));
    }

    // ...其他必要的方法重写
}

为了能够解析JSON格式的消息体,你需要引入适当的依赖,比如Jackson或者Gson等。如果你使用的是Maven构建工具,可以在pom.xml中添加如下依赖:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version> <!-- 确保使用最新稳定版本 -->
</dependency>

URL路径/查询参数

你也可以在WebSocket握手时通过URL路径或查询参数传递数据。这通常用于传递一些初始化信息,例如用户ID、会话令牌等。

后端代码示例(Java)

import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

public class MyWebSocketHandler extends TextWebSocketHandler {

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 获取URL中的查询参数
        MultiValueMap<String, String> queryParams = session.getUri().getQueryParams();
        // 或者从path variables中获取
        // String userId = (String) session.getAttributes().get("userId");

        super.afterConnectionEstablished(session);
    }

    // ...其他方法
}

在上述示例中,可以通过session.getUri()来获取原始的WebSocket URL,并从中提取出任何路径变量或查询参数。

这些参数可以在连接建立后立即使用,或者存储起来供后续消息处理时使用。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文