后端代码实现一个webSocket的服务端,消息精准推送和批量推送代码如下:
@ServerEndpoint(value = "/websocket")
@Component
@Slf4j
public class WebSocketServer {
// 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
private static Map<String, CopyOnWriteArraySet<WebSocketServer>> socketMap = new HashMap();
// 与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
String userId = this.session.getQueryString();
if (userId != null && !"".equals(userId)) {
if (socketMap.get(userId) == null) {
CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
webSocketSet.add(this);
socketMap.put(userId, webSocketSet);
} else {
socketMap.get(userId).add(this);
}
}
addOnlineCount(); // 在线数加1
log.info("{}连接成功!", userId);
HashMap<String, String> map = new HashMap<>();
map.put("msg", "连接成功");
sendMessage(JSONObject.toJSONString(map));
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
String userId = this.session.getQueryString();
CopyOnWriteArraySet<WebSocketServer> webSocketServers = socketMap.get(userId);
webSocketServers.remove(this);
subOnlineCount(); // 在线数减1
log.info("{}连接关闭!当前在线人数为{}", userId, getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
/*log.info("来自客户端的消息:" + message);
// 群发消息
for (WebSocketServer item : socketMap.get("")) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}*/
}
/**
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误", error);
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) {
try {
this.session.getBasicRemote().sendText(message);
log.info("消息发送成功:{}", message);
} catch (IOException e) {
log.error("消息发送失败", e);
}
}
/**
* 群发自定义消息
*/
public static void sendInfo(MessageDTO message) throws IOException {
if (message.getReceiveUserId() != null && !"".equals(message.getReceiveUserId())) {
// 全局发送消息
if ("0".equals(message.getReceiveUserId())) {
socketMap.forEach((k, v) -> {
for (WebSocketServer item : v) {
item.sendMessage(JSONObject.toJSONString(message));
}
});
} else if (socketMap.get(message.getReceiveUserId()) != null) {
for (WebSocketServer item : socketMap.get(message.getReceiveUserId())) {
item.sendMessage(JSONObject.toJSONString(message));
}
} else {
log.error("没有找到消息发送的目标对象");
}
} else {
log.error("没有找到消息发送的目标对象");
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
前端代码实现消息接收:
<!DOCTYPE HTML>
<html>
<head>
<title>My WebSocket</title>
</head>
<body>
Welcome<br/>
<input id="text" type="text" /><button onclick="send()">Send</button> <button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>
<script type="text/javascript">
var websocket = null;
//判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
websocket = new WebSocket("ws://127.0.0.1:9049/websocket?sring");
}
else{
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function(){
setMessageInnerHTML("error");
};
//连接成功建立的回调方法
websocket.onopen = function(event){
setMessageInnerHTML("open");
}
//接收到消息的回调方法
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function(){
setMessageInnerHTML("close");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function(){
websocket.close();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//关闭连接
function closeWebSocket(){
websocket.close();
}
//发送消息
function send(){
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>