Spring Boot中使用原生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>

3. 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,并从中提取出任何路径变量或查询参数。这些参数可以在连接建立后立即使用,或者存储起来供后续消息处理时使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值