1. 程式人生 > >WebSocket 在 SpringBoot 中的使用

WebSocket 在 SpringBoot 中的使用

介紹

WebSocket 是 HTML5 開始提供的一種在單個 TCP 連線上進行全雙工通訊的協議。

WebSocket 使得客戶端和伺服器之間的資料交換變得更加簡單,允許服務端主動向客戶端推送資料。在 WebSocket API 中,瀏覽器和伺服器只需要完成一次握手,兩者之間就直接可以建立永續性的連線,並進行雙向資料傳輸。

在 WebSocket API 中,瀏覽器和伺服器只需要做一個握手的動作,然後,瀏覽器和伺服器之間就形成了一條快速通道。兩者之間就直接可以資料互相傳送。

現在,很多網站為了實現推送技術,所用的技術都是 Ajax 輪詢。輪詢是在特定的的時間間隔(如每1秒),由瀏覽器對伺服器發出HTTP請求,然後由伺服器返回最新的資料給客戶端的瀏覽器。這種傳統的模式帶來很明顯的缺點,即瀏覽器需要不斷的向伺服器發出請求,然而HTTP請求可能包含較長的頭部,其中真正有效的資料可能只是很小的一部分,顯然這樣會浪費很多的頻寬等資源。

HTML5 定義的 WebSocket 協議,能更好的節省伺服器資源和頻寬,並且能夠更實時地進行通訊。

瀏覽器通過 JavaScript 向伺服器發出建立 WebSocket 連線的請求,連線建立以後,客戶端和伺服器端就可以通過 TCP 連線直接交換資料。

當你獲取 Web Socket 連線後,你可以通過 send() 方法來向伺服器傳送資料,並通過 onmessage 事件來接收伺服器返回的資料。

以下 API 用於建立 WebSocket 物件。

WebSocket協議

WebSocket並不是全新的協議,而是利用了HTTP協議來建立連線。我們來看看WebSocket連線是如何建立的。

首先,WebSocket連線必須由瀏覽器發起,因為請求協議是一個標準的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請求有幾點不同:

  1. GET請求的地址不是類似/path/,而是以ws://開頭的地址;
  2. 請求頭Upgrade: websocket
    Connection: Upgrade表示這個連線將要被轉換為WebSocket連線;
  3. Sec-WebSocket-Key是用於標識這個連線,並非用於加密資料;
  4. Sec-WebSocket-Version指定了WebSocket的協議版本。

隨後,伺服器如果接受該請求,就會返回如下響應:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: server-random-string

該響應程式碼101表示本次連線的 HTTP 協議即將被更改,更改後的協議就是Upgrade: websocket指定的WebSocket協議。

版本號和子協議規定了雙方能理解的資料格式,以及是否支援壓縮等等。如果僅使用WebSocket的API,就不需要關心這些。

現在,一個WebSocket連線就建立成功,瀏覽器和伺服器就可以隨時主動傳送訊息給對方。訊息有兩種,一種是文字,一種是二進位制資料。通常,我們可以傳送JSON格式的文字,這樣,在瀏覽器處理起來就十分容易。

為什麼 WebSocket 連線可以實現全雙工通訊而HTTP連線不行呢?實際上 HTTP 協議是建立在 TCP 協議之上的,TCP 協議本身就實現了全雙工通訊,但是 HTTP 協議的請求-應答機制限制了全雙工通訊。WebSocket 連線建立以後,其實只是簡單規定了一下:接下來,咱們通訊就不使用HTTP協議了,直接互相發資料吧。

安全的WebSocket連線機制和HTTPS類似。首先,瀏覽器用wss://xxx建立WebSocket連線時,會先通過HTTPS建立安全的連線,然後,該 HTTPS 連線升級為 WebSocket 連線,底層通訊走的仍然是安全的 SSL/TLS 協議。

瀏覽器

很顯然,要支援WebSocket通訊,瀏覽器得支援這個協議,這樣才能發出ws://xxx的請求。目前,支援WebSocket的主流瀏覽器如下:

  • Chrome
  • Firefox
  • IE >= 10
  • Sarafi >= 6
  • Android >= 4.4
  • iOS >= 8

SpringBoot 中 WebSocket 的使用

加入 maven 依賴

SpringBoot 2.0 之後,直接導此包即可:

<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的內建容器
 *     不需要注入ServerEndpointExporter, 它將由容器自己提供和管理
 * @author zhangchuanqiang
 */
@Configuration
public class WebSocketConfig {
	@Bean
	public ServerEndpointExporter serverEndpointExporter() {
		return new ServerEndpointExporter();
	}
}

WebSocketServer

websocket 伺服器,相當於一個ws協議的 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 {
	/**
	 * 初始線上人數
	 */
	private static AtomicInteger online_num = new AtomicInteger(0);
	/**
	 * 執行緒安全的socket集合,儲存線上使用者例項
	 */
	private static CopyOnWriteArraySet<MySocket> webSocketSet = new CopyOnWriteArraySet<MySocket>();
	/**
	 * 當前會話
	 */
	private Session session;

	/**
	 * 接收使用者id
	 */
	private String sid = "";

	/**
	 * 連線建立成功呼叫的方法
	 */
	@OnOpen
	public void onOpen(Session session, @PathParam("sid") String sid) {
		this.sid = sid;
		this.session = session;
		webSocketSet.add(this);
		// 線上人數+1
		addOnlineCount();
		log.info("有連結加入,當前人數為:" + getOnline_num());
		sendMessageBasic("有連結加入,當前人數為:" + getOnline_num());
	}

	/**
	 * 連線關閉呼叫的方法
	 */
	/**
	 * 連線關閉呼叫的方法
	 */
	@OnClose
	public void onClose() {
		webSocketSet.remove(this);
		subOnlineCount(); //線上數減1
		log.info("有一連線關閉!當前線上人數為" + getOnline_num());
	}

	/**
	 * 收到客戶端訊息後呼叫的方法
	 *
	 * @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("發生錯誤");
		error.printStackTrace();
	}

	/**
	 * 實現伺服器主動推送
	 */
	public void sendMessageBasic(String message) {
		try {
			this.session.getBasicRemote().sendText(message);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 實現伺服器主動推送
	 */
	public void sendMessageAsync(String message) {
		this.session.getAsyncRemote().sendText(message);
	}

	/**
	 * 群發自定義訊息
	 */
	public static void sendInfo(String message, @PathParam("sid") String sid) throws IOException {
		log.info("推送訊息到視窗" + sid + ",推送內容:" + message);
		for (MySocket item : webSocketSet) {
			//這裡可以設定只推送給這個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: 推送資料介面
 * @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);
}

頁面發起 socket 請求

協議是 ws 或者 wss,可以封裝了一些 basePath 的路徑類,可以replace(“http”,“ws”)來替換協議。

<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;
    //判斷當前瀏覽器是否支援WebSocket
    if ('WebSocket' in window) {
        // Websocket 使用 ws 或 wss 的統一資源標誌符,類似於 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')
    }

    //連線發生錯誤的回撥方法
    onlinenum.onerror = function () {
        setMessageInnerHTML("error");
    };

    //連線成功建立的回撥方法
    onlinenum.onopen = function (event) {
        setMessageInnerHTML("open");
    }

    //接收到訊息的回撥方法
    onlinenum.onmessage = function (event) {
        setMessageInnerHTML(event.data);
    }

    //連線關閉的回撥方法
    onlinenum.onclose = function () {
        setMessageInnerHTML("close");
    }

    //監聽視窗關閉事件,當視窗關閉時,主動去關閉websocket連線,防止連線還沒斷開就關閉視窗,server端會拋異常。
    window.onbeforeunload = function () {
        onlinenum.close();
    };

    //將訊息顯示在網頁上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //關閉連線
    function closeWebSocket() {
        onlinenum.close();
    }

    //傳送訊息
    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 註解。

資料