欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring Boot 整合單機(jī)websocket的步驟 附github源碼

 更新時(shí)間:2021年10月08日 11:14:49   作者:jeremylai  
websocket 是一個(gè)通信協(xié)議,通過(guò)單個(gè) TCP 連接提供全雙工通信,這篇文章主要介紹了Spring Boot 整合單機(jī)websocket的步驟(附github源碼),需要的朋友可以參考下

websocket 概念

websocket 是一個(gè)通信協(xié)議,通過(guò)單個(gè) TCP 連接提供全雙工通信。websocket 連接成功后,服務(wù)端和客戶可以進(jìn)行雙向通信。不同于 http 通信協(xié)議需要每次由客戶端發(fā)起,服務(wù)響應(yīng)到客戶端。
websocket 相對(duì)輪詢也能節(jié)約帶寬,并且能實(shí)時(shí)的進(jìn)行通信。

整合步驟

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 創(chuàng)建 bean

這個(gè) bean 會(huì)自動(dòng)注冊(cè)聲明 @ServerEndpoint 注解聲明的 websocket endpoint,使用springboot自帶tomcat啟動(dòng)需要該配置,使用獨(dú)立 tomcat 則不需要該配置。

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

3. 創(chuàng)建服務(wù)端端點(diǎn) (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】有新的連接,總數(shù):{}",webSocketSet.size());
	}

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

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

	/**
	 * 發(fā)送消息
	 * @param message
	 * @return 全部都發(fā)送一遍
	 */
	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頁(yè)面

<!DOCTYPE html>
<html>
<head>
    <title>websocket</title>
</head>
<body>
<div>
    <input type="text" name="message" id="message">
    <button id="sendBtn">發(fā)送</button>
</div>
<div style="width:100px;height: 500px;" id="content">
</div>
<script src="https://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源碼

到此這篇關(guān)于Spring Boot 整合單機(jī)websocket 附github源碼的文章就介紹到這了,更多相關(guān)Spring Boot 整合websocket內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot異常: nested exception is java.lang.NoClassDefFoundError: javax/servlet/ServletContext解決方案

    SpringBoot異常: nested exception is java.lang.NoClassDefFoundE

    這篇文章主要介紹了SpringBoot異常: nested exception is java.lang.NoClassDefFoundError: javax/servlet/ServletContext解決方案,說(shuō)明了錯(cuò)誤原因和解決方案,需要的朋友可以參考下
    2021-06-06
  • java基礎(chǔ)之標(biāo)簽、按鈕和按鈕事件簡(jiǎn)介

    java基礎(chǔ)之標(biāo)簽、按鈕和按鈕事件簡(jiǎn)介

    本文給大家?guī)?lái)的是java圖形界面的基礎(chǔ)知識(shí),簡(jiǎn)單介紹了標(biāo)簽、按鈕和按鈕事件,十分的詳細(xì),有需要的小伙伴可以參考下。
    2015-06-06
  • 最新評(píng)論