1. 程式人生 > 其它 >java Springboot搭建websocket 服務端和html客戶端程式碼

java Springboot搭建websocket 服務端和html客戶端程式碼

這塊 網上案例挺多的 本來也不準備寫 但是 反正也是接觸到了 寫下來 也算做個記錄

第一步、引入jar包

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

springboot專案 自帶websocket就直接引入了

第二步、搭建websocket服務

  • WebSocketConfig
package com.jinfu.sdkdemo.websocket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
@EnableWebSocket
public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpoint() { return new ServerEndpointExporter(); } }
  • wobsocket服務
package com.jinfu.sdkdemo.websocket;
import lombok.extern.slf4j.Slf4j;import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.util.concurrent.ConcurrentHashMap; /** * @ServerEndpoint 通過這個 spring boot 就可以知道你暴露出去的 websockst 應用的路徑,有點類似我們經常用的@RequestMapping。比如你的啟動埠是8080,而這個註解的值是ws,那我們就可以通過 ws://127.0.0.1:8080/websocket 來連線你的應用 * @OnOpen 當 websocket 建立連線成功後會觸發這個註解修飾的方法,注意它有一個 Session 引數 * @OnClose 當 websocket 建立的連線斷開後會觸發這個註解修飾的方法,注意它有一個 Session 引數 * @OnMessage 當客戶端傳送訊息到服務端時,會觸發這個註解修改的方法,它有一個 String 入參表明客戶端傳入的值 * @OnError 當 websocket 建立連線時出現異常會觸發這個註解修飾的方法,注意它有一個 Session 引數 */ @ServerEndpoint("/websocket/{id}") @Component @Slf4j public class WebSocketServer {/** * concurrent包的執行緒安全Set,用來存放每個客戶端對應的WebSocketController物件。 */ private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>(); //與某個客戶端的連線會話,需要通過它來給客戶端傳送資料 private Session session; /** * 接收id */ private String id; /** * 連線建立成功呼叫的方法 */ @OnOpen public void onOpen(Session session, @PathParam("id") String id) { this.session = session; this.id = id; //如果已經包含該使用者id,則移除後重新加入 if (webSocketMap.containsKey(id)) { webSocketMap.remove(id); webSocketMap.put(id, this); } else { //否則直接加入 webSocketMap.put(id, this); } } /** * 連線關閉呼叫的方法 */ @OnClose public void onClose() { if (webSocketMap.containsKey(id)) { webSocketMap.remove(id); log.info(">>> 使用者:{}已關閉連線", id); } else { log.info(">>> 連線已關閉..."); } } /** * 收到客戶端訊息後呼叫的方法 * * @param message 客戶端傳送過來的訊息 */ @OnMessage public void onMessage(String message, Session session){ //接收傳過來的訊息 System.out.println("收到的訊息:"+message);
     //傳送訊息
     sendMessage("傳送訊息"); } /** * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { log.error(">>> WebSocket出現未知錯誤: "); error.printStackTrace(); } /** * 實現伺服器主動推送 */ public void sendMessage(String message){ try { this.session.getBasicRemote().sendText(message); } catch (Exception e) { log.error(">>> WebSocket訊息傳送出現錯誤: "); e.printStackTrace(); } } }

上面websockst的服務端就搭建好了

第三步、websocket客戶端,也就是前端的websocket連線

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta charset="utf-8"/>
    <title>首頁</title>
</head>
<body>
<input type="button" value="傳送" onclick="send()">
<div id="title">

</div>
<!-- js部分 -->
<script type="text/javascript" th:src="@{/jquery-3.2.1.min.js}"></script>
<script>
    var ws;
    openWebSocket();
    function openWebSocket(){
        if ("WebSocket" in window) {
            //如果已經有連線,則斷開並重新連線
            if (ws != null) {
                ws.close();
                ws = null;
            }
            // 建立一個 websocket
       var UUID = 123;
ws = new WebSocket("ws://localhost:8080/websocket/"+UUID); ws.onopen = function () { console.log('WebSocket連線已建立') }; //獲得訊息事件 ws.onmessage = function (evt) { $("#title").html('<p>接收:'+evt.data+'</p>'); }; ws.onclose = function () { console.log('WebSocket連線已斷開') }; } else { // 瀏覽器不支援 WebSocket console.log('您的瀏覽器不支援 WebSocket!'); } } function send(){ ws.send("傳送一條訊息"); }</script> </body> </html>

到這裡 結束 總體上來說 很簡單 玩一次後面就會了