java实现websocket服务端

本文介绍了如何在SpringBoot项目中使用WebSocket技术,包括添加依赖、配置WebSocket服务器端点、设置消息缓冲大小,以及客户端的连接方式。作者还提供了使用Postman进行测试的建议。

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

Java实现websocket

导入依赖

			<dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-websocket</artifactId>
                <version>1.5.20.RELEASE</version>
            </dependency>

编写websocket配置类

1.因为使用@ServerEndpoint实现websocket连接,所以需要进行ServerEndpointExporter配置
2.onStartup进行websocket交互时,发送数据大小限制的配置

@Configuration
public class WebSocketConfig {

    /**
     * 注入ServerEndpointExporter,
     * 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
     */

    @Bean
    public ServletContextInitializer initializer() {
        return new ServletContextInitializer() {
            @Override
            public void onStartup(ServletContext servletContext) {
                // 设置WebSocket文本消息的最大缓冲区大小为25MB
                servletContext.setInitParameter("org.apache.tomcat.websocket.textBufferSize", "26214400");
                // 如果需要,也可以设置二进制消息的最大缓冲区大小
                // servletContext.setInitParameter("org.apache.tomcat.websocket.binaryBufferSize", "52428800");
            }
        };
    }
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

编写websocket服务端

@Component
@ServerEndpoint("/my-websocket")
public class WebSocketServer {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);

    private static final ConcurrentMap<String, Session> SESSIONS = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        LOGGER.info("New WebSocket connection opened: {}", session.getId());
    }

    @OnMessage
    public void onMessage(Session session, String message) {

        LOGGER.info("receive message : {}", message);
        SESSIONS.put("xxxx",session);
        try {
            sedSession.getBasicRemote().sendText(forwardingJson.toString());
            
        } catch (Exception e) { // Catch all exceptions for simplicity, but you should handle specific exceptions separately.
            LOGGER.error("Error processing WebSocket message", e);
            throw new RuntimeException("Error processing message", e);
        }
    }

    @OnClose
    public void onClose(Session session) {
        //todo: delete the session
        LOGGER.info("WebSocket connection closed: {}", session.getId());
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        LOGGER.error("WebSocket connection error", throwable);
    }

    private void removeSession(ConcurrentMap<String, Session> map, Session sessionToRemove) {
        map.entrySet().removeIf(entry -> Objects.equals(entry.getValue(), sessionToRemove));
    }
}

客户端交互:
非加密:ws://localhost:8080/my-websocket
加 密:wss://localhost:8080/my-websocket

推荐测试工具:postman

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值