packagecom.jeecg.webSocket;importnet.sf.json.JSONObject;import javax.websocket.*;importjavax.websocket.server.PathParam;importjavax.websocket.server.ServerEndpoint;importjava.io.IOException;importjava.util.Map;importjava.util.concurrent.ConcurrentHashMap;
@ServerEndpoint("/webSocket/{username}")public classWebSocket {private static int onlineCount = 0;private static Map clients = new ConcurrentHashMap();privateSession session;privateString username;
@OnOpenpublic void onOpen(@PathParam("username") String username, Session session) throwsIOException {this.username =username;this.session =session;
addOnlineCount();
clients.put(username,this);
System.out.println("已连接");
}
@OnClosepublic void onClose() throwsIOException {
clients.remove(username);
subOnlineCount();
}
@OnMessagepublic void onMessage(String message) throwsIOException {
JSONObject jsonTo=JSONObject.fromObject(message);
String mes= (String) jsonTo.get("message");if (!jsonTo.get("To").equals("All")){
sendMessageTo(mes, jsonTo.get("To").toString());
}else{
sendMessageAll("给所有人");
}
}
@OnErrorpublic voidonError(Session session, Throwable error) {
error.printStackTrace();
}public void sendMessageTo(String message, String To) throwsIOException {for(WebSocket item : clients.values()) {if(item.username.equals(To) )
item.session.getAsyncRemote().sendText(message);
}
}public void sendMessageAll(String message) throwsIOException {for(WebSocket item : clients.values()) {
item.session.getAsyncRemote().sendText(message);
}
}public static synchronized intgetOnlineCount() {returnonlineCount;
}public static synchronized voidaddOnlineCount() {
WebSocket.onlineCount++;
}public static synchronized voidsubOnlineCount() {
WebSocket.onlineCount--;
}public static synchronized MapgetClients() {returnclients;
}
}