介紹
WebSocket 是 HTML5 開始提供的一種在單個 TCP 連接上進行全雙工通訊的協(xié)議绍刮。
WebSocket 使得客戶端和服務(wù)器之間的數(shù)據(jù)交換變得更加簡單来氧,允許服務(wù)端主動向客戶端推送數(shù)據(jù)酷愧。在 WebSocket API 中箕昭,瀏覽器和服務(wù)器只需要完成一次握手歌憨,兩者之間就直接可以創(chuàng)建持久性的連接叶雹,并進行雙向數(shù)據(jù)傳輸财饥。
在 WebSocket API 中,瀏覽器和服務(wù)器只需要做一個握手的動作折晦,然后钥星,瀏覽器和服務(wù)器之間就形成了一條快速通道。兩者之間就直接可以數(shù)據(jù)互相傳送满着。
現(xiàn)在谦炒,很多網(wǎng)站為了實現(xiàn)推送技術(shù),所用的技術(shù)都是 Ajax 輪詢漓滔。輪詢是在特定的的時間間隔(如每1秒)编饺,由瀏覽器對服務(wù)器發(fā)出HTTP請求,然后由服務(wù)器返回最新的數(shù)據(jù)給客戶端的瀏覽器响驴。這種傳統(tǒng)的模式帶來很明顯的缺點透且,即瀏覽器需要不斷的向服務(wù)器發(fā)出請求,然而HTTP請求可能包含較長的頭部,其中真正有效的數(shù)據(jù)可能只是很小的一部分秽誊,顯然這樣會浪費很多的帶寬等資源鲸沮。
HTML5 定義的 WebSocket 協(xié)議,能更好的節(jié)省服務(wù)器資源和帶寬锅论,并且能夠更實時地進行通訊讼溺。
瀏覽器通過 JavaScript 向服務(wù)器發(fā)出建立 WebSocket 連接的請求,連接建立以后最易,客戶端和服務(wù)器端就可以通過 TCP 連接直接交換數(shù)據(jù)怒坯。
當(dāng)你獲取 Web Socket 連接后,你可以通過 send() 方法來向服務(wù)器發(fā)送數(shù)據(jù)藻懒,并通過 onmessage 事件來接收服務(wù)器返回的數(shù)據(jù)剔猿。
以下 API 用于創(chuàng)建 WebSocket 對象。
WebSocket協(xié)議
WebSocket并不是全新的協(xié)議嬉荆,而是利用了HTTP協(xié)議來建立連接归敬。我們來看看WebSocket連接是如何創(chuàng)建的。
首先鄙早,WebSocket連接必須由瀏覽器發(fā)起汪茧,因為請求協(xié)議是一個標(biāo)準(zhǔn)的HTTP請求,格式如下:
GET ws://localhost:3000/ws/chat HTTP/1.1
Host: localhost
Upgrade: websocket
Connection: Upgrade
Origin: http://localhost:3000
Sec-WebSocket-Key: client-random-string
Sec-WebSocket-Version: 13
該請求和普通的HTTP請求有幾點不同:
- GET請求的地址不是類似
/path/
限番,而是以ws://
開頭的地址舱污; - 請求頭
Upgrade: websocket
和Connection: Upgrade
表示這個連接將要被轉(zhuǎn)換為WebSocket連接; -
Sec-WebSocket-Key
是用于標(biāo)識這個連接扳缕,并非用于加密數(shù)據(jù)慌闭; -
Sec-WebSocket-Version
指定了WebSocket的協(xié)議版本。
隨后躯舔,服務(wù)器如果接受該請求驴剔,就會返回如下響應(yīng):
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: server-random-string
該響應(yīng)代碼101
表示本次連接的 HTTP 協(xié)議即將被更改,更改后的協(xié)議就是Upgrade: websocket
指定的WebSocket協(xié)議粥庄。
版本號和子協(xié)議規(guī)定了雙方能理解的數(shù)據(jù)格式丧失,以及是否支持壓縮等等。如果僅使用WebSocket的API惜互,就不需要關(guān)心這些布讹。
現(xiàn)在,一個WebSocket連接就建立成功训堆,瀏覽器和服務(wù)器就可以隨時主動發(fā)送消息給對方描验。消息有兩種,一種是文本坑鱼,一種是二進制數(shù)據(jù)膘流。通常絮缅,我們可以發(fā)送JSON格式的文本,這樣呼股,在瀏覽器處理起來就十分容易耕魄。
為什么 WebSocket 連接可以實現(xiàn)全雙工通信而HTTP連接不行呢?實際上 HTTP 協(xié)議是建立在 TCP 協(xié)議之上的彭谁,TCP 協(xié)議本身就實現(xiàn)了全雙工通信吸奴,但是 HTTP 協(xié)議的請求-應(yīng)答機制限制了全雙工通信。WebSocket 連接建立以后缠局,其實只是簡單規(guī)定了一下:接下來则奥,咱們通信就不使用HTTP協(xié)議了,直接互相發(fā)數(shù)據(jù)吧甩鳄。
安全的WebSocket連接機制和HTTPS類似逞度。首先,瀏覽器用wss://xxx
創(chuàng)建WebSocket連接時妙啃,會先通過HTTPS創(chuàng)建安全的連接,然后俊戳,該 HTTPS 連接升級為 WebSocket 連接揖赴,底層通信走的仍然是安全的 SSL/TLS 協(xié)議。
瀏覽器
很顯然抑胎,要支持WebSocket通信燥滑,瀏覽器得支持這個協(xié)議,這樣才能發(fā)出ws://xxx
的請求阿逃。目前铭拧,支持WebSocket的主流瀏覽器如下:
- Chrome
- Firefox
- IE >= 10
- Sarafi >= 6
- Android >= 4.4
- iOS >= 8
SpringBoot 中 WebSocket 的使用
加入 maven 依賴
SpringBoot 2.0 之后,直接導(dǎo)此包即可:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>1.5.10.RELEASE</version>
</dependency>
WebSocketConfig
開啟 websocket 支持恃锉,如果是使用獨立的 servlet 容器(如tomcat)搀菩,則不需要注入 ServerEndpointExporter
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* 開啟 websocket 支持<br>
* 配置WebSocketEndpointServer
* 如果使用獨立的servlet容器,不是使用SpringBoot的內(nèi)置容器
* 不需要注入ServerEndpointExporter, 它將由容器自己提供和管理
* @author zhangchuanqiang
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
WebSocketServer
websocket 服務(wù)器破托,相當(dāng)于一個ws協(xié)議的 Controller
import lombok.extern.java.Log;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @Description: WebSocketServer
* @Author: zcq
* @Date: 2019-06-14 14:37
*/
@Log
@Component
@ServerEndpoint("/index/{sid}") //該注解表示該類被聲明為一個webSocket終端
public class MySocket {
/**
* 初始在線人數(shù)
*/
private static AtomicInteger online_num = new AtomicInteger(0);
/**
* 線程安全的socket集合肪跋,存儲在線用戶實例
*/
private static CopyOnWriteArraySet<MySocket> webSocketSet = new CopyOnWriteArraySet<MySocket>();
/**
* 當(dāng)前會話
*/
private Session session;
/**
* 接收用戶id
*/
private String sid = "";
/**
* 連接建立成功調(diào)用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam("sid") String sid) {
this.sid = sid;
this.session = session;
webSocketSet.add(this);
// 在線人數(shù)+1
addOnlineCount();
log.info("有鏈接加入,當(dāng)前人數(shù)為:" + getOnline_num());
sendMessageBasic("有鏈接加入土砂,當(dāng)前人數(shù)為:" + getOnline_num());
}
/**
* 連接關(guān)閉調(diào)用的方法
*/
/**
* 連接關(guān)閉調(diào)用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this);
subOnlineCount(); //在線數(shù)減1
log.info("有一連接關(guān)閉州既!當(dāng)前在線人數(shù)為" + getOnline_num());
}
/**
* 收到客戶端消息后調(diào)用的方法
*
* @param message
* @param session
* @throws IOException
*/
@OnMessage
public void onMessage(String message, Session session) throws IOException {
log.info("來自客戶端的消息:" + message);
for (MySocket item : webSocketSet) {
item.sendMessageBasic(message);
}
}
/**
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.info("發(fā)生錯誤");
error.printStackTrace();
}
/**
* 實現(xiàn)服務(wù)器主動推送
*/
public void sendMessageBasic(String message) {
try {
this.session.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 實現(xiàn)服務(wù)器主動推送
*/
public void sendMessageAsync(String message) {
this.session.getAsyncRemote().sendText(message);
}
/**
* 群發(fā)自定義消息
*/
public static void sendInfo(String message, @PathParam("sid") String sid) throws IOException {
log.info("推送消息到窗口" + sid + ",推送內(nèi)容:" + message);
for (MySocket item : webSocketSet) {
//這里可以設(shè)定只推送給這個sid的萝映,為null則全部推送
if (sid == null || "all".equals(sid)) {
item.sendMessageBasic(message);
} else if (item.sid.equals(sid)) {
item.sendMessageBasic(message);
}
}
}
public static MySocket getWebSocket(String sid) {
if (webSocketSet == null || webSocketSet.size() <= 0) {
return null;
}
for (MySocket item : webSocketSet) {
if (sid.equals(item.sid)) {
return item;
}
}
return null;
}
public AtomicInteger getOnline_num() {
return MySocket.online_num;
}
public int subOnlineCount() {
return MySocket.online_num.addAndGet(-1);
}
public int addOnlineCount() {
return MySocket.online_num.addAndGet(1);
}
}
推送消息
/**
* @Description: 頁面請求
* @Author: zcq
* @Date: 2019-06-14 14:35
*/
@GetMapping("/socket/{cid}")
public ModelAndView socket(@PathVariable String cid) {
ModelAndView mav = new ModelAndView("/index1");
mav.addObject("cid", cid);
return mav;
}
/**
* @Description: 推送數(shù)據(jù)接口
* @Author: zcq
* @Date: 2019-06-14 14:35
* @param cid 為 all 時吴叶,為推送全部
*/
@ResponseBody
@RequestMapping("/socket/push/{cid}")
public Result pushToWeb(@PathVariable String cid, String message) {
try {
MySocket.sendInfo(message, cid);
} catch (IOException e) {
e.printStackTrace();
return Result.error();
}
return Result.success(cid);
}
頁面發(fā)起 socket 請求
協(xié)議是 ws 或者 wss,可以封裝了一些 basePath
的路徑類序臂,可以replace(“http”,“ws”)
來替換協(xié)議蚌卤。
<html>
<head>
<meta charset="utf-8">
<title>My WebSocket</title>
</head>
<body>
Welcome<br/>
<input id="text" type="text"/>
<button onclick="send()">Send</button>
<button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>
<script type="text/javascript">
var websocket = null;
//判斷當(dāng)前瀏覽器是否支持WebSocket
if ('WebSocket' in window) {
// Websocket 使用 ws 或 wss 的統(tǒng)一資源標(biāo)志符,類似于 HTTPS,其中 wss 表示在 TLS 之上的 Websocket造寝。
// onlinenum = new WebSocket("ws://localhost:8086/websocket/20");
onlinenum = new WebSocket("http://localhost:8086/websocket/${cid}".replace("http", "ws").replace("https", "ws"));
} else {
alert('Not support websocket')
}
//連接發(fā)生錯誤的回調(diào)方法
onlinenum.onerror = function () {
setMessageInnerHTML("error");
};
//連接成功建立的回調(diào)方法
onlinenum.onopen = function (event) {
setMessageInnerHTML("open");
}
//接收到消息的回調(diào)方法
onlinenum.onmessage = function (event) {
setMessageInnerHTML(event.data);
}
//連接關(guān)閉的回調(diào)方法
onlinenum.onclose = function () {
setMessageInnerHTML("close");
}
//監(jiān)聽窗口關(guān)閉事件磕洪,當(dāng)窗口關(guān)閉時,主動去關(guān)閉websocket連接诫龙,防止連接還沒斷開就關(guān)閉窗口析显,server端會拋異常搔驼。
window.onbeforeunload = function () {
onlinenum.close();
};
//將消息顯示在網(wǎng)頁上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//關(guān)閉連接
function closeWebSocket() {
onlinenum.close();
}
//發(fā)送消息
function send() {
const message = document.getElementById('text').value;
onlinenum.send(message);
}
</script>
</html>
問題補充:
- 如果希望打成WAR包移斩,部署到TOMCAT中。需要使啟動類繼承:SpringBootServletInitializer吸申,并加入方法:
/**
* 用于支持打包成 WAR锦聊,部署到 tomcat 中
*/
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(AssetApplication.class);
}
- 如果打成WAR包后歹嘹,在TOMCAT中啟動時報錯:Multiple Endpoints may not be deployed to the same path 注釋掉 WebSocketServer 類上的 @Component 注解。