我在使用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);
}
這個方法是異步的,你放在調用後面還沒有執行到。