1. 在頁面a.html頁面定義一個websocket
var websocket = null;
//判斷目前浏覽器是否支援WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket(
"ws://ip:端口/項目名/websocket?a");
} else {
layer.alert('您的浏覽器不支援websocket,需要手動重新整理b頁面!');
}
2. 在a.html中相應的觸發位置添加
websocket.send();
3.服務端代碼
@ServerEndpoint(value = "/websocket")
public class MyWebSocket {
//a與b頁面的連接配接會話,需要通過它來給b發送資料
private Session session;
/**
* 連接配接建立成功調用的方法
* @param session 可選的參數
* @throws Exception
*/
@OnOpen
public void onOpen(Session session) throws Exception {
this.session = session;
WebSocketMap.put(session.getQueryString(), this);
}
/**
* 連接配接關閉調用的方法
* @throws Exception
*/
@OnClose
public void onClose() throws Exception {
//從map中删除
WebSocketMap.remove(session.getQueryString());
}
/**
* 收到a消息後調用的方法
* @param message 用戶端發送過來的消息
* @param session 可選的參數
* @throws IOException
*/
@OnMessage
public void onMessage(String message, Session session) throws IOException {
try {
this.sendMessages(message);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 發生錯誤時調用
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
/**
* 發送消息方法。
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 給b發消息方法。
* @param message
* @throws IOException
*/
public void sendMessages(String message) throws IOException {
MyWebSocket myWebSocket = WebSocketMap.get("b");
myWebSocket.sendMessage(message);
}
}
4.服務端使用的Map類
public class WebSocketMap {
public static ConcurrentMap<String, MyWebSocket> webSocketMap = new ConcurrentHashMap<>();
public static void put(String key, MyWebSocket myWebSocket) {
webSocketMap.put(key, myWebSocket);
}
public static MyWebSocket get(String key) {
return webSocketMap.get(key);
}
public static void remove(String key) {
webSocketMap.remove(key);
}
public static Collection<MyWebSocket> getValues() {
return webSocketMap.values();
}
}
5.在b.html頁面中同樣定義websocket
var websocket = null;
//判斷目前浏覽器是否支援WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket(
"ws://ip:端口/項目名/websocket?b");
} else {
layer.alert('您的浏覽器不支援websocket,需要手動重新整理b頁面!');
}
6.接收a發送來的消息,重新整理b頁面
websocket.onmessage = function(event) { };