WebSocket再整理-以及集成websocket以后单元测试无法使用的bug解决

本文探讨了WebSocket Server中如何通过多例模式管理和利用session,避免每次都保存当前连接对象。作者揭示了会话映射的真正目的和bean复用的机制,以及在实际操作中的优化策略,包括使用userId查找其他用户会话进行消息响应。
摘要由CSDN通过智能技术生成

有如下代码,
代码是从另外的博主那里改一改得到的,因为注入了对象,所以不希望每次向Map都保存当前的websocektServer,就改为了只保存session,后来发现有些地方需要用到userId,心想糟了,这不得是null啊,结果却意外的发现,能正常执行;

debug时发现每一次连接创建时的this当前对象内存地址都不一样,而关闭时是一样的。。。
由于基础不牢,一下无法理解发生了什么。创建了一个Controller测试了一下发现,每次请求进入时当前bean又是相同的地址;

我最后的临时理解就是,含有@OnOpen注解的bean会变成多例模式,每一次连接就是一个独立的对象,
代码中的map容器保存会话的初衷并非给一个无状态的bean通过usrId找到自己使用的,而是给其他连接的对象调用查询指定用户会话使用的;
每一次连接进入时都会有特定的机制匹配对应的对象,那样无论是执行@OnClose还是@OnMessage时,this都会是创建连接时的那个对象,并没有必要通过map拿会话,直接使用成员变量session属性即可;
原博主的代码中成员变量有一个session属性,被我删掉了,后来改成了根据userid从map中拿,原博主的方法没有错,当需要向自身响应消息的时候,直接使用session进行响应即可。因为在open时就对这个属性进行了赋值,同时赋值的还有userid。当执行close|message操作时由于匹配了对应的bean,所以属性是有值的可以直接执行,我这里就直接不用了,通过userId匹配算了,反正也只有在连接成功和权限不足的时候会使用session直接响应消息,多数时刻是从map中get其他用户的session进行响应

想法:
有没有那么一种可能。我不通过会话map进行取 其他用户的会话,我直接从ioc中拿到其他用户的bean,使用他们的session属性进行消息响应,当前,前提是要加上原博主的session成员属性

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

/**
 * @author guochao
 */
///websocket/infoCar/eyJhbGciOiJIUzI1NiJ9.eyJpZCI6NTU4LCJleHAiOjE2NTAwMTQ4MDQsInZlcnNpb24iOiJhZGNmZWIwZC05MDE3LTRhODUtYWE3Mi1iZTQ2NDA0MmE0ZTMifQ.p-LRvG07U0kyCa0aJZo8ediJrqaa7vGDJUMnVPaO_uE
@ServerEndpoint("/websocket/infoCar/{token}")
@Component
@Lazy
public class WebSocketServer {

    static Log log = LogFactory.get(WebSocketServer.class);
    /**
     * 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private  static int onlineCount = 0;
    /**
     * concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
     *  2022.3.18:修改为只保存绘画session,共用功能方法,减少开销。如果日后出现问题请使用备份
     */
    private static ConcurrentHashMap<String, Session> webSocketMap = new ConcurrentHashMap<>();
    /**
     * 接收userId,由于每个会话对应一个对象,所以这里在调用方法时始终有值,直到关闭
     */
    private String userId ;
    private final WebSocketService webSocketService = SpringUtil.getBean(WebSocketService.class);
    private final CheckToken checkToken = SpringUtil.getBean(CheckToken.class);

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) throws IOException {
        User user = checkToken.queryUserByToken(token);
        if (StringUtils.isBlank(token) || ObjectUtils.isEmpty(user)) {
            session.getAsyncRemote().sendText(JSONObject.toJSONString(new WebSocketMsgView(false, CodeEnum.TOKEN_INVALID.getCode()
                    ,WsRespTypeEnum.TOKEN_INVALID.getType(),WsRespTypeEnum.TOKEN_INVALID.getMsg())));
            throw new RuntimeException("websocket通讯中token无效");
        }
        this.userId = String.valueOf(user.getId());
        log.info("连接成功,用户:{}", userId);
        System.out.println();
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, session);
            //加入set中
        } else {
            webSocketMap.put(userId, session);
            //加入set中
            addOnlineCount();
            //在线数加1
        }
        log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
        //连接成功时
        String msgJson = JSONObject.toJSONString(new WebSocketMsgView(true, 20000,
                WsRespTypeEnum.OPEN_SUCCESS.getType(),  WsRespTypeEnum.OPEN_SUCCESS.getMsg()));
        try {
            sendToSession(session,msgJson);
            //sendInfo(userId,msgJson);
        } catch (IOException e) {
            log.error("用户:" + userId + ",网络异常!!!!!!");
        }
        // maxKeepAliveRequests
    }

    /**
     * 连接关闭调用的方法,每次关闭的时候,时使用和open一样的对象调用的,所以userId有值
     */
    @OnClose
    public void onClose() {
        log.info("连接关闭");
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }
        log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session,@PathParam("token") String token) throws IOException {
        log.info("用户消息:" + userId + ",报文:" + message);
        //可以群发消息
        //消息保存到数据库、redis
        if (StringUtils.isNotBlank(message)) {
            try {
                //解析发送的报文,封装为ws来参obj
                WebSocketParam webSocketParam = JSON.parseObject(message).toJavaObject(WebSocketParam.class);
                User user = checkToken.queryUserByToken(webSocketParam.getToken());
                //根据类型获取对应的响应信息
                WsRequest wsRequest = webSocketService.wsController(user, webSocketParam);
                //编辑接收人
                String recUser = wsRequest.getRecUser().toString();
                //生成json
                String jsonResult = JSONObject.toJSONString(wsRequest.getWebSocketMsgView());
                //发送json
                if (StringUtils.isNotBlank(recUser) && webSocketMap.containsKey(recUser)) {
                    sendToSession( webSocketMap.get(recUser),jsonResult);
                } else {
                    sendInfo(userId,JSON.toJSONString(webSocketService.userUnOnline(Long.parseLong(userId)).getWebSocketMsgView()));
                    log.error("请求的userId:" + recUser + "不在该服务器上");
                }
            } catch (JSONException e) {
                WebSocketMsgView webSocketMsgView = webSocketService.badParam(Long.parseLong(userId)).getWebSocketMsgView();
                sendInfo(userId,JSON.toJSONString(webSocketMsgView));
                log.error("报文解析异常,报文:{},会话:{},异常:",message,session,e);
            } catch (Exception e){
                log.error("websocketError:",e);
            }
        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 向session输出消息
     */
    private void sendToSession(Session session,String message) throws IOException {
        session.getBasicRemote().sendText(message);
    }


    /**
     * 发送自定义消息
     */
    public void sendInfo(@PathParam("userId") String userId,String message) throws IOException {
        log.info("发送消息到:" + userId + ",报文:" + message);
        if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)) {
            sendToSession(webSocketMap.get(userId),message);
        } else {
            log.error("用户" + userId + ",不在线!");
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}

补充:

当Springboot集成了websocket以后使用单元测试时会报错
javax.websocket.server.ServerContainer not available
这是由单元测试时并不会启动服务器,所以造成websocket报错
我们可以在测试注解中添加配置,让他启动以一个服务器环境
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
public class DataUtil {
    @Autowired
    private MeModuleService meModuleService;

    @Test
    public void testMe(){
        Result<MeModuleView> test = meModuleService.getMeModuleViewTest(1531573333810884610L);
        System.out.println(test);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值