springboot整合WebSocket示例

本文详细介绍了如何在SpringBoot项目中使用WebSocket进行客户端与服务器之间的实时通信,包括WebSocket配置、服务器端处理用户连接、消息传递以及错误处理。实例演示了客户端如何通过JavaScript实现与服务器的交互。

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

springboot整合WebSocket简单示例

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
package com.tianyu.websocket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

//启用WebSocket配置类
@Configuration
public class WebSocketConfig {
   
   
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
   
   
        return new ServerEndpointExporter();
    }
}
package com.tianyu.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;

//WebSocketServer服务类
@ServerEndpoint("/ws/{userId}")
@Component
@Slf4j
public class WebSocketServer {
   
   

    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    //接收userId
    private String userId = "";

    //连接建立成功调用的方法
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
   
   
        this.session = session;
        this.userId = userId;
        if (webSocketMap.containsKey(userId)) {
   
   
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
        } else {
   
   
            webSocketMap.put(userId, this);
            addOnlineCount();
        }
        log.info(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值