|
1. 加一个uid字段标识当前websocket对象,方便后续关闭时从map中移除和直接查找消息发送目标用户。
2. webSocketHashMap改为ConcurrentHashMap
3. 去掉onlineCount,获取在线人数使用websocketmap.size()
@OnClose
public void onClose() {
webSocketHashMap.remove(this.uid);// webSocketHashMap.remove(this);不能从map中移除当前已关闭的websocket对象
...
}
@OnMessage
public void onMessage(String message, Session session) {
logger.debug("来自客户端的消息:" + message);
JSONObject json = JSON.parseObject(message);
JSONObject jsonObject = (JSONObject) json.get("data");
String to = jsonObject.get("to").toString();
try {
if (webSocketHashMap.containsKey(to)) { // for (String key : webSocketHashMap.keySet()) { ... }
((WebSocket) webSocketHashMap.get(to))
.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
完整代码:
package com.jeecg.chat.web;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeecg.chat.entity.ChatMessageHistory;
import com.jeecg.chat.service.ChatMessageHistoryService;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
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;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.jeecgframework.p3.core.logger.Logger;
import org.jeecgframework.p3.core.logger.LoggerFactory;
import org.jeecgframework.p3.core.utils.common.ApplicationContextUtil;
import org.springframework.context.ApplicationContext;
@ServerEndpoint("/WebSocket/{id}")
public class WebSocket {
private static final Logger logger = LoggerFactory.getLogger(WebSocket.class);
private static Map<String, WebSocket> webSocketHashMap = new ConcurrentHashMap<String, WebSocket>();
private Session session;
private String uid;
private ChatMessageHistoryService chatMessageHistoryService;
@OnOpen
public void onOpen(@PathParam("id") String id, Session session) {
this.session = session;
this.uid = id;
webSocketHashMap.put(id, this);
logger.info("有新连接加入!当前在线人数为" + getOnlineCount());
ApplicationContext ctx = ApplicationContextUtil.getContext();
if (ctx.containsBean("chatMessageHistoryService"))
this.chatMessageHistoryService = ((ChatMessageHistoryService) ctx
.getBean("chatMessageHistoryService"));
}
@OnClose
public void onClose() {
webSocketHashMap.remove(this.uid);
logger.info("有一连接关闭!当前在线人数为" + getOnlineCount());
}
@OnMessage
public void onMessage(String message, Session session) {
logger.debug("来自客户端的消息:" + message);
JSONObject json = JSON.parseObject(message);
JSONObject jsonObject = (JSONObject) json.get("data");
String to = jsonObject.get("to").toString();
ChatMessageHistory messageHistory = new ChatMessageHistory();
messageHistory.setFromName(jsonObject.getString("fromName"));
messageHistory.setFromUser(jsonObject.getString("from"));
messageHistory.setToName(jsonObject.getString("toName"));
messageHistory.setToUser(jsonObject.getString("to"));
messageHistory.setMsgType(json.getString("type"));
messageHistory.setMsg(jsonObject.getString("msg"));
String randomSeed = UUID.randomUUID().toString().replaceAll("-", "")
.toUpperCase();
messageHistory.setId(randomSeed);
this.chatMessageHistoryService.insert(messageHistory);
messageHistory = null;
try {
if (webSocketHashMap.containsKey(to)) {
((WebSocket) webSocketHashMap.get(to))
.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@OnError
public void onError(Session session, Throwable error) {
logger.info("发生错误");
error.printStackTrace();
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
public static synchronized int getOnlineCount() {
return webSocketHashMap.size();
}
}
|
|