java websocket向前端實時推送消息


part1:

@Configuration
public class WebSocketConfig {

@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}

part2:
@ServerEndpoint("/websocket/{id}")
@Component
@Slf4j
@EnableScheduling
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 ("id") String sid) {
this.session = session;
webSocketSet.add(this); // 加入 set 中
addOnlineCount(); // 在線數加 1
log.info("有新窗口開始監聽 :" +sid+ ", 當前在線人數為 " + getOnlineCount());
this.sid =sid;

try {
sendMessage("連接成功");
} 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);
// 群發消息
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);
}


/**
* 群發自定義消息
* */
public static void sendInfo(String message, @PathParam("sid") String sid) {
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;
}
}
}

@Scheduled(cron = "0/2 * * * * ?")
private void autoSendInfo() {
log.info("客戶端個數:" + webSocketSet.size());

for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(item.sid + "11111");
} 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--;
}
}

測試html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM