1、創建WebSocketServer
@ServerEndpoint("/websocket/{sid}")
@Component // 成分、組件
public class WebSocketServer {
//靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。
private static int onlineCount = 0;
//用來存放每個客戶端對應的WebSocket對象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
//與某個客戶端的連接會話,需要通過它來給客戶端發送數據
private Session session;
//接收sid
private String sid="";
/**
* 連接建立成功調用的方法
*/
@OnOpen
public void onOpen(Session session,@PathParam("sid") String sid) {
this.sid=sid;
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在線數加1
LogUtil.log.info("有新窗口開始監聽:"+sid+",當前在線人數爲" + getOnlineCount());
try {
sendMessage("連接成功...");
} catch (IOException e) {
LogUtil.log.error("websocket IO異常");
}
}
/**
* 連接關閉調用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //從set中刪除
subOnlineCount(); //在線數減1
LogUtil.log.info("有一連接關閉!當前在線人數爲" + getOnlineCount());
}
/**
* 收到客戶端消息後調用的方法
* @param message 客戶端發送過來的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
LogUtil.log.info("收到來自窗口"+sid+"的信息:"+message);
//羣發消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
LogUtil.log.error("發生錯誤");
error.printStackTrace();
}
/**
* 實現服務器主動推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 羣發自定義消息
*/
public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {
LogUtil.log.info("推送消息到窗口"+sid+",推送內容:"+message);
for (WebSocketServer item : webSocketSet) {
try {
//這裏可以設定只推送給這個sid的,爲null則全部推送
if(sid==null) {
item.sendMessage(message);
}else if(item.sid.equals(sid)){
item.sendMessage(message);
}
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
public static WebSocketServer getWebSocket(String sid) {
if (webSocketSet == null || webSocketSet.size() <= 0) {
return null;
}
for (WebSocketServer item : webSocketSet) {
if (sid.equals(item.sid)) {
return item;
}
}
return null;
}
}
2、用戶登錄成功後判斷
WebSocketServer wss = WebSocketServer.getWebSocket(String.valueOf(adminInfo.getAid()));
if (wss != null) { // 如果已經登錄,則發送擠退信息
try {
wss.sendMessage("101");
} catch (IOException e) {
e.printStackTrace();
}
}
3、用戶在前臺登錄成功後,發送連接信息給服務器
function openWebSocket(sid) { // sid爲當前登錄用戶的id
var socket;
if(typeof(WebSocket) == undefined) {
console.log("您的瀏覽器不支持WebSocket");
}else{
//實現化WebSocket對象,指定要連接的服務器地址與端口 建立連接
socket = new WebSocket("ws://127.0.0.1:8080/EduMagSys/websocket/"+sid);
//打開事件
socket.onopen = function() {
console.log("Socket 已打開");
//socket.send("這是來自客戶端的消息" + location.href + new Date());
};
//獲得消息事件
socket.onmessage = function(msg) {
if (msg.data == "101") {
alert("對不起,你的賬號已經在其它地方登錄,若非本人操作,請及時更換密碼...");
location.href="../login.html";
return;
}
};
//關閉事件
socket.onclose = function() {
console.log("Socket已關閉");
};
//發生了錯誤事件
socket.onerror = function() {
alert("Socket發生了錯誤");
};
$(window).unload(function(){
socket.close();
});
}
}