初次使用 WebSocket -springboot 集成

參考自:SpringBoot 集成websocket_清泉影月的博客-CSDN博客WebSocket中利用service層交互數據庫_戒菸的李白的博客-CSDN博客_websocketservice

核心依賴

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

<!--用於把字符串轉json 可不配置-->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>

配置類

import com.deloitte.WebsocketServer.WebSocketServer;
import com.deloitte.mapper.system.SysUsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {

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

//用來配置交互數據庫 直接使用@Autowired 空指針 @Autowired
private void SysUsersMapper(SysUsersMapper sysUsersMapper){ WebSocketServer.sysUsersMapper=sysUsersMapper; } }

服務

@Component
@Service
@ServerEndpoint("/websocket/{clientId}")
public class WebSocketServer {



    //靜態變量,用來記錄當前在線連接數
    private static int onlineCount = 0;

    //用來存放每個客戶端對應的的連接信息
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();

    //與某個客戶端的連接會話,需要通過它來給客戶端發送數據
    private Session session;

    //連接的 clientId
    private String clientId = "";

    /**
     * 前端連接建立成功調用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("clientId") String clientId) {
        this.session = session;
        this.clientId = clientId;
        webSocketSet.add(this);
        addOnlineCount();
        try {
            String msg = "clientId:" + clientId + "連接成功,當前在線客戶端數:" + getOnlineCount();
            sendMessage(msg);
            System.err.println(msg);

        } catch (IOException e) {
            System.err.println("client:{},連接故障,原因:{}"+ clientId+ e.getMessage());
        }
    }

    /**
     * 前端連接關閉調用的方法
     * 可以在裏面寫一些關閉連接需要處理的邏輯
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        subOnlineCount();
        System.err.println("釋放連接,clientId:{};當前連接數:{}"+ clientId+getOnlineCount());
    }


    public static SysUsersMapper sysUsersMapper; //換成自己的

    /**
     * 該方法用於接受客戶端發送的消息
     * 當前邏輯是:相同 clientId 的連接可以接受消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {

       // System.err.println("收到來自clientId:{} 的消息:{}"+clientId+ message);

        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<String, Object>();
        map = gson.fromJson(message, map.getClass());
        System.err.println(map.get("frozen"));
        String s=map.get("frozen")+"";
        sysUsersMapper.savelog(s,s,s,s, s, s);


        for (WebSocketServer item : webSocketSet) {
            try {
                if (item.clientId.equals(clientId)) {   //廣播發送的話就去掉if
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                System.err.println("client:{} 發送消息故障,原因:{}"+ item.clientId+ e.getMessage());
            }
        }
    }

    /**
     * 用於記錄發生的錯誤
     */
    @OnError
    public void onError(Session session, Throwable e) {
        System.err.println("出現故障:{}"+e.getMessage());
    }

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

    /**
     * 定向 clientId 發送消息
     */
    public void sendInfo(String clientId, String message) throws IOException {
        System.err.println("推送消息到clientId:{},msg:{}"+clientId+message);
        for (WebSocketServer item : webSocketSet) {
            if (item.clientId.equals(clientId)) {
                item.sendMessage(message);
            }
        }
    }

    /**
     * 羣發消息,廣播形式
     */
    public void sendInfoAll(String message) throws IOException {
        for (WebSocketServer item : webSocketSet) {
            item.sendMessage(message);
        }
    }

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

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

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

    public static CopyOnWriteArraySet<WebSocketServer> getWebSocketSet() {
        return webSocketSet;
    }
}

附測試地址:websocket在線測試 (websocket-test.com)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章