1. 程式人生 > 其它 >java websocket向前端實時推送訊息

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--;
}
}