webSocket单独向用户发送消息

2019-06-19  本文已影响0人  闲置的Programmer

1、先将websocke整体框架搭建完成
https://www.jianshu.com/writer#/notebooks/36919459/notes/46633169

2、在OnOpen()方法建立连接的时候,把连接时传过来的ID存到websocetSet对象中

/**
     * @param deviceId 当前发消息的人员编号 与机器绑定
     * @param session 客户端发送数据对象
     * @throws IOException
     */
    @OnOpen
    public void onOpen(@PathParam("deviceId")String deviceId, Session session,EndpointConfig config) throws IOException {
        try{
            System.out.println("机器编号:"+ deviceId);
            this.deviceId = deviceId;//接收到发送消息的人员编号

            this.session = session;
            webSocketSet.put(this.deviceId,this);

            addOnlineCount();           //在线数加1
            System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());

            //获取service
            this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
            if(httpSession != null){
                ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(httpSession.getServletContext());
                userService = (UserService) ctx.getBean("userService");
                meaService = (MeaService) ctx.getBean("meaService");
                advertisingService = (AdvertisingService) ctx.getBean("advertisingService");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

3、然后在websocket的OnMessage方法中通过if判断当前连接ID与要发送消息过来的连接ID是否相同,相同则恢复消息

 //发送消息
    public void sendMessageToRobot(String robotId,JSONObject bigJson) throws IOException{
        if (StringUtils.isEmpty(webSocketSet.get(robotId))) {
            System.out.println("当前机器不在线");
        } else {
            if(!deviceId.equals(robotId)){
//                System.out.println("1当前deviceId : "+deviceId+" 发送消息后,给robotId : " +robotId+"机器发送消息");
//                System.out.println("sendMessage : "+bigJson.toString());
//                webSocketSet.get(robotId).sendMessage(bigJson.toString());
            } else{
                System.out.println("2当前deviceId : "+deviceId+" 发送消息后,给robotId : "+ robotId+"机器发送消息");
                System.out.println("sendMessage : "+bigJson.toString());
                webSocketSet.get(robotId).sendMessage(bigJson.toString());
            }
        }
    }


上一篇下一篇

猜你喜欢

热点阅读