柚子快報(bào)激活碼778899分享:java集成WebSocket
柚子快報(bào)激活碼778899分享:java集成WebSocket
package com.xzst.kafka.websocket;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component;
import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap;
/**
WebSocket 服務(wù)器 @author liukexin @date 2024/06/12 */ @ServerEndpoint(“/websocketServer/{userId}”) @Component public class WebSocketServer { private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class); /**
靜態(tài)變量,用來(lái)記錄當(dāng)前在線連接數(shù)。應(yīng)該把它設(shè)計(jì)成線程安全的。 / private static int onlineCount = 0; /*concurrent包的線程安全Set,用來(lái)存放每個(gè)客戶端對(duì)應(yīng)的MyWebSocket對(duì)象。 / private static final ConcurrentHashMap
連接建立成功調(diào)用的方法 */ @OnOpen public void onOpen(Session session, @PathParam(“userId”) String userId) { this.session = session; this.userId = userId; WEB_SOCKET_MAP.put(userId, this); //在線數(shù)加1 addOnlineCount(); log.info(“用戶連接:{},當(dāng)前在線人數(shù)為:{}”, userId, getOnlineCount()); try { sendMessage(“連接成功”); } catch (IOException e) { log.error(“用戶:{},網(wǎng)絡(luò)異常!!!”, userId); } } /**
連接關(guān)閉調(diào)用的方法 */ @OnClose public void onClose() { WEB_SOCKET_MAP.remove(userId); //從set中刪除 subOnlineCount(); log.info(“用戶退出:{},當(dāng)前在線人數(shù)為:{}”, userId, getOnlineCount()); } /**
收到客戶端消息后調(diào)用的方法@param message 客戶端發(fā)送過(guò)來(lái)的消息 */ @OnMessage public void onMessage(String message, Session session) { log.info(“用戶消息:{},報(bào)文:{}”, userId, message); //可以群發(fā)消息 //消息保存到數(shù)據(jù)庫(kù)、redis if (StringUtils.isNotBlank(message)) { try { //解析發(fā)送的報(bào)文 JSONObject jsonObject = JSON.parseObject(message); //追加發(fā)送人(防止串改) jsonObject.put(“fromUserId”, this.userId); String toUserId = jsonObject.getString(“toUserId”); //傳送給對(duì)應(yīng)toUserId用戶的websocket if (StringUtils.isNotBlank(toUserId) && WEB_SOCKET_MAP.containsKey(toUserId)) { WEB_SOCKET_MAP.get(toUserId).sendMessage(jsonObject.toJSONString()); } else { log.error(“請(qǐng)求的userId:{}不在該服務(wù)器上”, toUserId); //否則不在這個(gè)服務(wù)器上,發(fā)送到mysql或者redis } } catch (Exception e) { e.printStackTrace(); } } } /**
出錯(cuò)時(shí)@param session 會(huì)話@param error 錯(cuò)誤 */ @OnError public void onError(Session session, Throwable error) { log.error(“用戶錯(cuò)誤:{},原因:{}”, this.userId, error.getMessage()); error.printStackTrace(); } /**
實(shí)現(xiàn)服務(wù)器主動(dòng)推送 */ public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); } /**
發(fā)送自定義消息 */ public static void sendInfo(String message, @PathParam(“userId”) String userId) throws IOException { log.info(“發(fā)送消息到:{},報(bào)文:{}”, userId, message); if (StringUtils.isNotBlank(userId) && WEB_SOCKET_MAP.containsKey(userId)) { WEB_SOCKET_MAP.get(userId).sendMessage(message); } else { log.error(“用戶{},不在線!”, userId); } } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { WebSocketServer.onlineCount++; } public static synchronized void subOnlineCount() { WebSocketServer.onlineCount–; } /**
@param userId 用戶id@param message 發(fā)送的消息@Title: sendMessageToUser@Description: 發(fā)送消息給用戶下的所有終端 */ public Boolean sendMessageToUser(String userId, String message) { if (WEB_SOCKET_MAP.containsKey(userId)) { log.debug(“給用戶id為:{}的所有終端發(fā)送消息:{}”, userId, message); WebSocketServer wS = WEB_SOCKET_MAP.get(userId); log.debug(“sessionId為:{}”, wS.session.getId()); try { wS.session.getBasicRemote().sendText(message); return true; } catch (IOException e) { e.printStackTrace(); log.debug(" 給用戶id為:{}發(fā)送消息失敗", userId); return false; } } log.debug(“發(fā)送錯(cuò)誤:當(dāng)前連接不包含id為:{}的用戶”, userId); return false; } }
柚子快報(bào)激活碼778899分享:java集成WebSocket
相關(guān)鏈接
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點(diǎn)和立場(chǎng)。
轉(zhuǎn)載請(qǐng)注明,如有侵權(quán),聯(lián)系刪除。