websocket路径配置备忘--以spring中配置为例

本文详细介绍了WebSocket服务端配置方法,包括定义服务器端接收和发送地址、客户端连接及消息交互过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
 * Name: WebSocketConfig.java
 * Title:
 * Description:
 * @copyright 2004-2018 Sichuan Tianyi Network Service Co.,Ltd All Rights Reserved。
 * @version v1.0.0 2016-4-25 14:19:09
 */
package com.tievd.cloud.vbp.message.config;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;
import org.springframework.web.socket.handler.WebSocketHandlerDecorator;
import org.springframework.web.socket.handler.WebSocketHandlerDecoratorFactory;

/**
 *
 * @author sitianqiang@tieserv.com
 */
@Configuration
@EnableWebSocketMessageBroker
@Order(Ordered.HIGHEST_PRECEDENCE + 99)
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    private Log LOG = LogFactory.getLog(WebSocketConfig.class);

    /**
     * 定义服务器端接改地址
     *
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        //服务端点接收客户端的连接
        registry.addEndpoint("/notify").setAllowedOrigins("*").withSockJS().setClientLibraryUrl("../js/1.1.4/sockjs.min.js");
    }

    /**
     * 定义服务器端发送地址
     *
     * @param config
     */
    @Override
    **public void configureMessageBroker(MessageBrokerRegistry config) {
        //客户端给服务端发消息的地址的前缀
        config.setApplicationDestinationPrefixes("/app");
        //客户端接收服务端消息的地址的前缀信息
        config.enableSimpleBroker("/topic", "/queue");
    }**
}

在以上服务端配置的情况下,js也有相应的写法:
连接websocket:很明显对应者registerStompEndpoints方法里的配置notify

var socket = new SockJS("http://master:8989/msg/notify/?access_token=" + token);  

订阅:对应于enableSimpleBroker方法

                stompClient.subscribe('/user/queue/face_compare', function(greeting){  

客户端向服务端发送消息:对应与setApplicationDestinationPrefixes方法

     stompClient.send("/app/hello", {atytopic:"greetings"}, JSON.stringify({ 'name': name }));  
### Spring Boot Starter WebSocket 与 Netty-WebSocket-Spring-Boot-Starter 对比分析 #### 性能方面 `netty-websocket-spring-boot-starter` 基于 Netty 实现,而 Netty 是一款异步事件驱动的网络应用框架,以其高吞吐量、低延迟和较小的资源消耗著称。因此,在处理大规模并发连接时,`netty-websocket-spring-boot-starter` 表现出更优异的性能[^1]。相比之下,`spring-boot-starter-websocket` 使用的是标准 Java API (`javax.websocket`) 或内置 Tomcat 容器支持的 WebSocket 功能,其性能虽然足以满足大多数场景需求,但在极端高并发情况下可能不如 Netty 高效[^3]。 #### 易用性方面 对于开发者而言,`spring-boot-starter-websocket` 提供了更为简洁直观的开发体验。它允许通过注解方式定义消息处理器,并且能够无缝集成到现有的 Spring 应用程序中,适合熟悉 Spring 生态系统的团队使用[^4]。然而,尽管 `netty-websocket-spring-boot-starter` 同样提供了良好的抽象层以简化开发流程,但由于底层依赖于 Netty,初学者可能会面临一定的学习曲线,尤其是在配置复杂功能或者调试问题时[^5]。 #### 场景适用性 当项目主要关注点在于快速搭建基础 Websocket 功能并希望保持较低的学习成本时,`spring-boot-starter-websocket` 是一个不错的选择;而对于那些需要更高性能指标的应用场合——比如实时聊天室、在线游戏服务器或者其他涉及大量数据交换的服务,则更适合采用 `netty-websocket-spring-boot-starter` 来获得更好的扩展性和稳定性。 另外值得注意的一点是,如果整个系统已经广泛采用了 Spring 技术栈并且不特别强调极致性能的话,继续沿用 `spring-boot-starter-websocket` 将有助于减少技术债务以及维护难度。反之,如果有计划迁移到更加灵活高效的通信机制之上,那么引入 `netty-websocket-spring-boot-starter` 则显得尤为必要。 ```java // 示代码展示两种starter的基本使用差异 // spring-boot-starter-websocket @ServerEndpoint("/ws") public class MyWebSocket { @OnMessage public String handleMessage(String message){ return "Received: "+message; } } // netty-websocket-spring-boot-starter 示 @Component public class MyNettyHandler extends TextWebSocketHandler{ @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { session.sendMessage(new TextMessage("Echo: "+message.getPayload())); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值