前端Vue
- 使用構造函數構建Websocket對象
WebSocket(url[, protocols])
- 對象的回調函數有:
WebSocket.onclose
用於指定連接關閉後的回調函數。
WebSocket.onerror
用於指定連接失敗後的回調函數。
WebSocket.onmessage
用於指定當從服務器接受到信息時的回調函數。
WebSocket.onopen
用於指定連接成功後的回調函數。
- 方法有:
關閉當前連接
WebSocket.close([code[, reason]])
發送數據
WebSocket.send(data)
示例:
data() {
return {
websock: null,
websocketUrl: "ws://localhost:8080/webSocketServer/"+this.$store.state.userTel,
};
},
methods: {
initWebSocket() {
//初始化weosocket
this.websock = new WebSocket(this.websocketUrl);
this.websock.onmessage = this.websocketonmessage;
this.websock.onopen = this.websocketonopen;
this.websock.onerror = this.websocketonerror;
this.websock.onclose = this.websocketclose;
},
//下面這些是回調函數
websocketonopen() {
//連接建立之後執行send方法發送數據
console.log("連接成功");
},
websocketonerror() {
//連接建立失敗重連
console.log("連接失敗重新連接");
this.initWebSocket();
},
//接受數據
websocketonmessage(e) {
console.log("接受數據");
let data = JSON.parse(e.data);
console.log(data);
},
//兩個方法
websocketsend(message) {
//數據發送
let data = {
"message": "hello world"
};
this.websock.send(JSON.stringify(data));
},
websocketclose() {
console.log("斷開連接");
},
created() {
this.initWebSocket();
},
destroyed() {
this.websock.close(); //離開路由之後斷開websocket連接
}
後端SpringBoot
在WebSocket應用程序中,服務器發佈一個WebSocket endpoint,客戶端使用這個endpoint的URI來連接到服務器.建立連接後,服務端和客戶端可以在連接打開的時候隨時發送消息.客戶端通常僅連接到一個服務器,而一個服務器接受來自多個客戶端的連接.
WebSocket協議有兩個部分 握手 和 數據傳輸
WebSocket URL格式:ws://host:port/path?query
- 使用註解創建WebSocket
- 發送消息
- 1.從連接中獲取Session對象
- 2.使用Session對象獲取RemoteEndpoint對象
- 3.使用RemoteEndpoint對象發送消息到對方
- 向所有連接方發送消息
獲取所有連接的Session,返回Set
從而可以使用遍歷到每個session對象發送消息
session.getOpenSessions()
- 接收消息
使用@OnMessage註解接收消息,每個@ServerEndpoint類最多可以有三個@OnMessage註解的方法,分別是:
@ServerEndpoint("/receive")
public class ReceiveEndpoint {
@OnMessage
public void textMessage(Session session, String msg) {
System.out.println("Text message: " + msg);
}
@OnMessage
public void binaryMessage(Session session, ByteBuffer msg) {
System.out.println("Binary message: " + msg.toString());
}
@OnMessage
public void pongMessage(Session session, PongMessage msg) {
System.out.println("Pong message: " +
msg.getApplicationData().toString());
}
}
編碼器
- 實現接口
- Encoder.Text for text messages
- Encoder.Binary for binary messages
- 將編碼器名稱加入到@ServerEndpoint中的可選參數encoders
- 使用sendObject(Object data)發送消息
解碼器
- 實現接口
- 將編碼器名稱加入到@ServerEndpoint中的可選參數decoders
- 使用@OnMessage的方法可以使用自定義的Java對象來作爲參數
僅做記錄,有更多理解之後再來完善
推薦博客:
https://blog.csdn.net/moshowgame/article/details/80275084
參考網址
https://docs.oracle.com/javaee/7/tutorial/websocket001.htm