q373005568
我自叹逍遥
采纳率75%
2015-11-13 09:04 阅读 1.5k
已采纳

关于WebSocket的小问题

我在使用WebSocket的时候发现,如果我把getBasicRemote().sendText()这个方法
在自己定义的WebSocket类的方法里面执行的时候正常,页面可以收到数据,但是如果是通过类里面的方法调用工具类,然后再执行getBasicRemote().sendText()这个方法,就会没有效果,哪位大神能帮我解答一下??

先贴上正常的代码

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

        System.out.println("Received: " + message);

        JSONArray ja = JSONArray.fromObject(message);
        JSONObject obj = ja.getJSONObject(0);
        Game game = (Game) JSONObject.toBean(obj,Game.class);

        String objStr = obj.toString();

        Set<String> keySet = UsersCtrl.getAllUser();
        Map<String, ChatUser> ulist = UsersCtrl.getUsers();
        ChatUser u = null;
        String uname = ulist.get(session+"").getUname();
        for (String key : keySet) {
            u = ulist.get(key);
            Session s = u.getSession();
            s.getBasicRemote().sendText(objStr);
        }

    }

接着上出错 的代码

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

        JSONArray ja = JSONArray.fromObject(message);
        JSONObject obj = ja.getJSONObject(0);
        Game game = (Game) JSONObject.toBean(obj, Game.class);

        WebSocketUtil.send(game);

    }

WebSocketUtil工具类内的方法

 public static void send(Game game){

        switch (game.getOperation()) {
        case "chat":
            chat(game.getRoom(), game.getMsg());
            break;

        default:
            break;
        }

    }

    public static void chat(String roomId, String msg){
        Map<String, GameUser> roomUsers = RoomUtil.
                getRoomUser(roomId).getUsers();

        sendToAll(roomUsers, msg);
    }
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

相关推荐