package com.reading.controller.library;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.server.standard.SpringConfigurator;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* Created by zz on 2018/9/6.
*/
@ServerEndpoint(value = "/websocket/{id}",configurator = SpringConfigurator.class)
public class MyWebSocket {
//靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。
private static int onlineCount = 0;
public MyWebSocket() {
}
//concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象。
// 若要實現服務端與單一客戶端通信的話,可以使用Map來存放,其中Key可以爲用戶標識
private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();
//與客戶端的連接會話,需要通過它來給客戶端發送數據
private Session session;
/**
* 連接建立成功調用的方法
* @param session 可選的參數。session爲與某個客戶端的連接會話,需要通過它來給客戶端發送數據
*/
@OnOpen
public void onOpen(Session session,EndpointConfig config,@PathParam("id") Integer id){
this.session = session;
//加入set中
webSocketSet.add(this);
//在線數加1
addOnlineCount();
System.out.println("有新連接加入!當前在線人數爲" + getOnlineCount());
}
/**
* 連接關閉調用的方法
*/
@OnClose
public void onClose(){
//從set中刪除
webSocketSet.remove(this);
//在線數減1
subOnlineCount();
System.out.println("有一連接關閉!當前在線人數爲" + getOnlineCount());
}
/**
* 收到客戶端消息後調用的方法
* @param message 客戶端發送過來的消息
* @param session 可選的參數
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("來自客戶端的消息:" + message);
//羣發消息
for(MyWebSocket item: webSocketSet){
// try {
// item.sendMessage(message);
// } catch (IOException e) {
// e.printStackTrace();
// continue;
// }
}
}
/**
* 發生錯誤時調用
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error){
System.out.println("發生錯誤");
error.printStackTrace();
}
/** * 這個方法與上面幾個方法不一樣。沒有用註解,是根據自己需要添加的方法。 * @param message * @throws IOException */ public void sendMessage(String message){ this.session.getAsyncRemote().sendText(message); }
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
MyWebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
MyWebSocket.onlineCount--;
}
}
T