spring boot +WebSocket 廣播式例項

weixin_34128411發表於2018-10-18

1. 專案介紹

  • 客戶端頁面index.html可以輸入訊息,點選傳送,通過ws協議傳送到伺服器端;
  • 伺服器端收到客戶端訊息後,廣播給各個客戶端;
  • 伺服器端頁面server.html,可以輸入訊息,點選傳送,通過ws雙工通訊推送給客戶端;
  • 客戶端有顯示伺服器端廣播訊息的區域。

2. 專案目錄結構

13930986-8449322dd514a030.png

3. 專案程式碼分析

3.1 pom.xml檔案新增必要依賴

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

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

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

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

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

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.7-1</version>
        </dependency>
    </dependencies>

3.2 .java程式碼

  • 新建WebSocket 的配置類WebSocketConfig.java
package com.springboot.websocket.websocket.config;

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

/**
 * WebSocket配置類
 *
 */
@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

  • WebSocket的服務端
package com.springboot.websocket.websocket.config;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * WebSocket的服務端
 * 因為WebSocket是類似客戶端服務端的形式(採用ws協議),
 * 那麼這裡的WebSocketServer其實就相當於一個ws協議的Controller
 * 直接@ServerEndpoint(“/websocket”)@Component啟用即可,
 * 然後在裡面實現@OnOpen,@onClose,@onMessage等方法
 */
@ServerEndpoint("/websocket")
@Component
public class WebSocketServer {

    //靜態變數,用來記錄當前線上連線數。應該把它設計成執行緒安全的。可選的
    private static int onlineCount = 0;
    //concurrent包的執行緒安全Set,用來存放每個客戶端對應的MyWebSocket物件。必須要有的
    private static CopyOnWriteArraySet<WebSocketServer>
            webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    //與某個客戶端的連線會話,需要通過它來給客戶端傳送資料,必須
    private Session session;

    /**
     * 連線建立成功呼叫的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //線上數加1
        //一旦連線成功後就在控制檯列印資訊
        System.out.println("有新視窗開始監聽,當前線上人數為" + getOnlineCount());
        try {
            //往客戶端傳送訊息
            sendMessage("連線成功");
        } catch (IOException e) {
            System.out.println("WebSocket IO異常");
        }
    }

    /**
     * 連線關閉呼叫的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //從set中刪除
        subOnlineCount();           //線上數減1
        System.out.println("有連線關閉!當前線上人數為" + getOnlineCount());
    }

    /**
     * 收到客戶端訊息後呼叫的方法
     *
     * @param message 客戶端傳送過來的訊息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        //message 是從客戶端傳送過來的訊息,並在控制檯列印
        System.out.println("收到客戶端的資訊:" + message);
        //群發訊息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("發生錯誤");
        error.printStackTrace();
    }

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


    /**
     * 群發自定義訊息
     */
    public static void sendInfo(String message) throws IOException {
        System.out.println("推送訊息內容:" + message);
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}

  • WebSocketController.java 控制層程式碼
package com.springboot.websocket.websocket.controller;

import com.springboot.websocket.websocket.config.WebSocketServer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;

/**

 * WebSocketController
 */
@Controller
@RequestMapping("/socket")
public class WebSocketController {


    /**
     * 輸入訊息的頁面
     * @return
     */
    @GetMapping("/send")
    public String sendMsg(){
        return "server";
    }

    /**
     * 推送資料介面
     * @Param message
     * @return
     */
    @RequestMapping("/push")
    public String pushMsg(@RequestParam("message")String message) {
        try {
            WebSocketServer.sendInfo(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "server";
    }
}

3.3 html頁面程式碼

  • 主頁面index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket</title>
</head>
<body>
<h1>WebScoket練習</h1>
<label>
    <input id="msg" type="text" name="message" style="width:215px;" />
    <input type="submit" id="btn" />
</label>
<br>


<div>
<ul id="message_show_ul">
</ul>
</div>
<script language="JavaScript">
    var send_message = document.getElementById("msg");
    var sub_button = document.getElementById("btn");
    var show_ul = document.getElementById("message_show_ul");
    var socket;
    if (typeof(WebSocket) == "undefined") {
        console.log("您的瀏覽器不支援WebSocket");
    } else {
        console.log("您的瀏覽器支援WebSocket");
        //實現化WebSocket物件,指定要連線的伺服器地址與埠建立連線
        socket = new WebSocket("ws://localhost:8088/websocket");

        //開啟事件
        socket.onopen = function () {
            console.log("Socket已開啟");
            sub_button.onclick = function () {
                console.log(send_message);
                //下面這句話是往伺服器傳送訊息
                socket.send("這是來自客戶端的訊息:" + send_message.value);
            };

        };

        //獲得訊息事件,從伺服器獲得訊息
        socket.onmessage = function (msg) {

            var li_eme = document.createElement("li");
            li_eme.innerHTML = msg.data;
            show_ul.appendChild(li_eme);
            //控制檯列印訊息
            console.log(msg.data);
            //彈出框彈出訊息
           // alert(msg.data);
        };

        //關閉事件
        socket.onclose = function () {
            console.log("Socket已關閉");
        };

        //發生了錯誤事件
        socket.onerror = function () {
            alert("Socket發生了錯誤");
        }
    }
</script>
</body>
</html>
  • 伺服器端頁面server.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocketServer</title>
</head>
<body>
<h1>伺服器端</h1>
<form id="login" action="/socket/push" method="get">
    <label>
        <input id="msg" type="text" name="message" style="width:215px;" />
        <input type="submit" id="btn"/>
    </label>
    <br>
</form>
</body>
</html>

相關文章