<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
import lombok.extern.slf4j.Slf4j; 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.List; import java.util.concurrent.CopyOnWriteArraySet; @Slf4j @Component @ServerEndpoint("/websocket/{sid}") public class WebSocketServer { //用來記錄當前在線鏈接數。 private static int onlineCount = 0; /** * concurrent包的線程安全Set,用來存放每一個客戶端對應的MyWebSocket對象。 */ public 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.session = session; webSocketSet.add(this); //加入set中 addOnlineCount();//在線數加1 log.info("有新窗口開始監聽:" + sid + ",當前在線人數爲" + getOnlineCount()); this.sid = sid; // try { // sendMessage("鏈接成功"); // sendInfo("當前鏈接用戶數:" + getOnlineCount(), null); // } catch (IOException e) { // log.error("websocket IO異常"); // } } /** * * 鏈接關閉調用的方法 * */ @OnClose public void onClose() { webSocketSet.remove(this); //從set中刪除 subOnlineCount(); //在線數減1 log.info("有一鏈接關閉!當前在線人數爲" + getOnlineCount()); } /** * * 收到客戶端消息後調用的方法 * * * * @param message 客戶端發送過來的消息 */ @OnMessage public void onMessage(String message, Session session) { log.info("收到來自窗口" + sid + "的信息:" + message); //單用戶sid try { WebSocketServer.sendInfo(message,sid); } catch (IOException e) { e.printStackTrace(); } // 羣發消息 // 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) { log.error("發生錯誤"); error.printStackTrace(); } /** * * 實現服務器主動推送 * */ public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); } /** * * 羣發自定義消息 * * 這裏能夠設定只推送給這個sid的,爲null則所有推送 */ public static void sendInfo(String message, @PathParam("sid") String sid) throws IOException { System.out.println("------WebSocketServer----------sendInfo-----"); 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--; } }