Spring Boot 整合單機websocket(附github源碼)

  • 2021 年 10 月 8 日
  • 筆記

websocket 概念

websocket 是一個通訊協議,通過單個 TCP 連接提供全雙工通訊。websocket 連接成功後,服務端和客戶可以進行雙向通訊。不同於 http 通訊協議需要每次由客戶端發起,服務響應到客戶端。
websocket 相對輪詢也能節約頻寬,並且能實時的進行通訊。

整合步驟

1. 添加 maven 依賴

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-websocket</artifactId>
	<version>2.1.3.RELEASE</version>
</dependency>
<dependency>
        <groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-freemarker</artifactId>
	<version>2.1.3.RELEASE</version>
</dependency>

添加web、websocket和freemarker依賴。

2. 使用 ServerEndpointExporter 創建 bean

這個 bean 會自動註冊聲明 @ServerEndpoint 註解聲明的 websocket endpoint,使用springboot自帶tomcat啟動需要該配置,使用獨立 tomcat 則不需要該配置。

@Configuration
public class WebSocketConfig {
    //tomcat啟動無需該配置
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

3. 創建服務端端點 (ServerEndpoint)

@Component
@ServerEndpoint(value = "/message")
@Slf4j
public class WebSocket {

	private static Map<String, WebSocket> webSocketSet = new ConcurrentHashMap<>();

	private Session session;

	@OnOpen
	public void onOpen(Session session) throws SocketException {
		this.session = session;
		webSocketSet.put(this.session.getId(),this);
		log.info("【websocket】有新的連接,總數:{}",webSocketSet.size());
	}

	@OnClose
	public void onClose(){
		String id = this.session.getId();
		if (id != null){
			webSocketSet.remove(id);
			log.info("【websocket】連接斷開:總數:{}",webSocketSet.size());
		}
	}

	@OnMessage
	public void onMessage(String message){
		if (!message.equals("ping")){
			log.info("【wesocket】收到客戶端發送的消息,message={}",message);
			sendMessage(message);
		}
	}

	/**
	 * 發送消息
	 * @param message
	 * @return 全部都發送一遍
	 */
	public void sendMessage(String message){
		for (WebSocket webSocket : webSocketSet.values()) {
			webSocket.session.getAsyncRemote().sendText(message);
		}
		log.info("【wesocket】廣播消息,message={}", message);

	}

}

4. 添加 controller 和 客戶端

  • 添加 controller
@GetMapping({"","index.html"})
public ModelAndView index() {
	ModelAndView view = new ModelAndView("index");
	return view;
}
  • 添加ftl頁面
<!DOCTYPE html>
<html>
<head>
    <title>websocket</title>
</head>
<body>
<div>
    <input type="text" name="message" id="message">
    <button id="sendBtn">發送</button>
</div>
<div style="width:100px;height: 500px;" id="content">
</div>
<script src="//cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script type="text/javascript">
    var ws = new WebSocket("ws://127.0.0.1:8080/message");
    ws.onopen = function(evt) {
        console.log("Connection open ...");
    };

    ws.onmessage = function(evt) {
        console.log( "Received Message: " + evt.data);
        var p = $("<p>"+evt.data+"</p>")
        $("#content").prepend(p);
        $("#message").val("");
    };

    ws.onclose = function(evt) {
        console.log("Connection closed.");
    };

    $("#sendBtn").click(function(){
        var aa = $("#message").val();
        ws.send(aa);
    })

</script>
</body>
</html>

5. 展示效果

效果

附錄

github源碼