WebSocket是一種在單個(gè)TCP連接上進(jìn)行全雙工通信的協(xié)議。WebSocket通信協(xié)議于2011年被IETF定為標(biāo)準(zhǔn)RFC 6455,并由RFC7936補(bǔ)充規(guī)范。WebSocket API也被W3C定為標(biāo)準(zhǔn)。
WebSocket使得客戶端和服務(wù)器之間的數(shù)據(jù)交換變得更加簡(jiǎn)單,允許服務(wù)端主動(dòng)向客戶端推送數(shù)據(jù)。在WebSocket API中,瀏覽器和服務(wù)器只需要完成一次握手,兩者之間就直接可以創(chuàng)建持久性的連接,并進(jìn)行雙向數(shù)據(jù)傳輸。
WebSocket優(yōu)點(diǎn)
較少的控制開(kāi)銷。在連接創(chuàng)建后,服務(wù)器和客戶端之間交換數(shù)據(jù)時(shí),用于協(xié)議控制的數(shù)據(jù)包頭部相對(duì)較小。在不包含擴(kuò)展的情況下,對(duì)于服務(wù)器到客戶端的內(nèi)容,此頭部大小只有2至10字節(jié)(和數(shù)據(jù)包長(zhǎng)度有關(guān));對(duì)于客戶端到服務(wù)器的內(nèi)容,此頭部還需要加上額外的4字節(jié)的掩碼。相對(duì)于HTTP請(qǐng)求每次都要攜帶完整的頭部,此項(xiàng)開(kāi)銷顯著減少了。
更強(qiáng)的實(shí)時(shí)性。由于協(xié)議是全雙工的,所以服務(wù)器可以隨時(shí)主動(dòng)給客戶端下發(fā)數(shù)據(jù)。相對(duì)于HTTP請(qǐng)求需要等待客戶端發(fā)起請(qǐng)求服務(wù)端才能響應(yīng),延遲明顯更少;即使是和Comet等類似的長(zhǎng)輪詢比較,其也能在短時(shí)間內(nèi)更多次地傳遞數(shù)據(jù)。
保持連接狀態(tài)。與HTTP不同的是,Websocket需要先創(chuàng)建連接,這就使得其成為一種有狀態(tài)的協(xié)議,之后通信時(shí)可以省略部分狀態(tài)信息。而HTTP請(qǐng)求可能需要在每個(gè)請(qǐng)求都攜帶狀態(tài)信息(如身份認(rèn)證等)。
更好的二進(jìn)制支持。Websocket定義了二進(jìn)制幀,相對(duì)HTTP,可以更輕松地處理二進(jìn)制內(nèi)容。
可以支持?jǐn)U展。Websocket定義了擴(kuò)展,用戶可以擴(kuò)展協(xié)議、實(shí)現(xiàn)部分自定義的子協(xié)議。如部分瀏覽器支持壓縮等。
更好的壓縮效果。相對(duì)于HTTP壓縮,Websocket在適當(dāng)?shù)臄U(kuò)展支持下,可以沿用之前內(nèi)容的上下文,在傳遞類似的數(shù)據(jù)時(shí),可以顯著地提高壓縮率。
握手協(xié)議
WebSocket 是獨(dú)立的、創(chuàng)建在 TCP 上的協(xié)議。
Websocket 通過(guò) HTTP/1.1 協(xié)議的101狀態(tài)碼進(jìn)行握手。
為了創(chuàng)建Websocket連接,需要通過(guò)瀏覽器發(fā)出請(qǐng)求,之后服務(wù)器進(jìn)行回應(yīng),這個(gè)過(guò)程通常稱為“握手”(handshaking)。
1.加依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6<version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.8.0.RELEASE<version>
</dependency>
2.WebSocketConfig類
package com.springboot.websocker.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* WebSocket的配置類
* 開(kāi)啟了WebSocket支持
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3.WebSocketServer類
package com.springboot.websocker.config;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
//客戶端向服務(wù)器端建立WebSocket連接的url
@ServerEndpoint("/websocket")
@Component
public class WebSocketServer {
//靜態(tài)變量,用來(lái)記錄當(dāng)前在線連接數(shù),可選
private static int onlineCount = 0;
//concurrent包的線程安全Set,用來(lái)存放每個(gè)客戶端對(duì)應(yīng)的MyWebSocket對(duì)象,必須
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet
= new CopyOnWriteArraySet<WebSocketServer>();
//與某個(gè)客戶端的連接會(huì)話,需要通過(guò)它來(lái)給客戶端發(fā)送數(shù)據(jù),必須
private Session session;
/**
* 連接建立成功調(diào)用的方法
*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //將客戶端加入set中
addOnlineCount(); //在線數(shù)加1
System.out.println("有新窗口開(kāi)始監(jiān)聽(tīng),當(dāng)前在線人數(shù)為"
+ getOnlineCount());
try {
sendMessage("連接成功");
} catch (IOException e) {
System.out.println("WebSocket IO異常");
}
}
/**
* 連接關(guān)閉調(diào)用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //從set中刪除
subOnlineCount(); //在線數(shù)減1
System.out.println("有連接關(guān)閉!當(dāng)前在線人數(shù)為" + getOnlineCount());
}
/**
* 收到客戶端消息后調(diào)用的方法
*
* @param message 客戶端發(fā)送過(guò)來(lái)的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("收到客戶端的信息:" + message);
//群發(fā)消息
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) {
System.out.println("發(fā)生錯(cuò)誤");
error.printStackTrace();
}
/**
* 實(shí)現(xiàn)服務(wù)器主動(dòng)推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群發(fā)自定義消息
*/
public static void sendInfo(String message) throws IOException {
System.out.println("推送消息內(nèi)容:" + message);
for (WebSocketServer item : webSocketSet) {
try {
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--;
}
}
4.WebSocketController類
package com.springboot.websocker.controller;
import com.springboot.websocker.config.WebSocketServer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
@RestController
public class WebSocketController {
//推送數(shù)據(jù)接口
@GetMapping("/socket/push")
public String pushMsg(String message) {
try {
WebSocketServer.sendInfo(message);
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
}
底層統(tǒng)統(tǒng)不要捕獲異常,所有的異常在controller捕獲異常
create和onload只執(zhí)行一次
5.前端代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>websocket示例</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<h3>消息顯示</h3>
<ul>
<li v-for="(message, index) in messages" :key="index">
{{message}}
</li>
</ul>
<hr>
<h3>發(fā)送消息 </h3>
<input type="text" v-model="sendMsg" />
<button type="button" @click="send">發(fā)送</button>
</div>
<script type="text/javascript">
var socket;
var app = new Vue({
el: '#app',
data: {
messages: [],
sendMsg: ''
},
created: function() {
var _this = this;
//創(chuàng)建WebSocket對(duì)象,指定要連接的服務(wù)器地址和端口,建立連接
socket = new WebSocket("ws://localhost:8080/websocket");
//打開(kāi)連接
socket.onopen = function() {
console.log("Socket已打開(kāi)");
};
//獲得服務(wù)端推送的消息
socket.onmessage = function(msg) {
console.log(msg.data);
_this.messages.push(msg.data);
console.log(_this.messages);
};
//關(guān)閉連接
socket.onclose = function() {
console.log("Socket已關(guān)閉");
};
//發(fā)送錯(cuò)誤
socket.onerror = function() {
alert("Socket發(fā)生了錯(cuò)誤");
}
},
watch: {
// 如果 `messages` 發(fā)生改變,這個(gè)函數(shù)就會(huì)運(yùn)行
messages: function(newMsg, oldMsg) {
/* this.messages = newMsg; */
var n = new Notification('Title', {
body :newMsg[newMsg.length - 1]
});
//兩秒后關(guān)閉通知
setTimeout(function() {
n.close();
}, 4000);
},
},
methods: {
send: function() {
socket.send(this.sendMsg);
}
}
})
</script>
</body>
</html>