feat: init websocket模块

This commit is contained in:
weihongyang
2022-06-29 16:29:25 +08:00
parent 8d6cda8f90
commit 6d792317dd
4 changed files with 168 additions and 0 deletions

View File

@@ -0,0 +1,79 @@
package com.cnbm.websocket.server;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
/**
* @Author weihongyang
* @Date 2022/6/29 8:59 AM
* @Version 1.0
*/
@Log4j2
@Component
@ServerEndpoint("/websocket/info") // 指定websocket 连接的url
public class WebSocketServer {
private static int onlineCount = 0;
public static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
private Session session;
private String sessionId;
@OnOpen
public void onOpen(Session session) {
log.info("客户端:{}连接成功",session.getId());
this.session = session;
this.sessionId = session.getId();
if (webSocketMap.containsKey(session.getId())){
webSocketMap.remove(sessionId);
webSocketMap.put(sessionId,this);
}else {
webSocketMap.put(sessionId,this);
addOnlineCount();
}
}
@OnClose
public void onClose(Session session) {
if (webSocketMap.containsKey(sessionId)) {
webSocketMap.remove(sessionId);
subOnlineCount();
}
log.info("客户端:{}连接断开",session.getId());
}
@OnMessage
public String onMsg(String message,Session session) {
log.info("从客户端:{} 收到<--:{}", session.getId(),message);
String send=message.toUpperCase();
String result="客户:%s您好来自server 的消息:%s";
result = String.format(result, session.getId(), send);
return "来自server 的消息:" + result;
}
public void sendMsg(String message) throws IOException{
this.session.getBasicRemote().sendText(message);
}
private static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
private static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}