【Java基礎(chǔ)】WebSocket在Spring中的使用

WebSocket

使用

關(guān)于怎么使用WebSocket,以及WebSocket的一些概念,這篇文章有做詳細(xì)的介紹。

為什么要使用WebSocket

我接觸到WebSocket,是因?yàn)橄胧褂肳ebSocket來替代HTTP 長(zhǎng)連接。

HTTP1.1通過使用Connection:keep-alive進(jìn)行長(zhǎng)連接,HTTP 1.1默認(rèn)進(jìn)行持久連接,在一次 TCP 連接中可以完成多個(gè) HTTP 請(qǐng)求,但是對(duì)每個(gè)請(qǐng)求仍然要單獨(dú)發(fā) header,Keep-Alive不會(huì)永久保持連接,它有一個(gè)保持時(shí)間,可以在不同的服務(wù)器軟件(如Apache)中設(shè)定這個(gè)時(shí)間,這種長(zhǎng)連接是一種“偽鏈接”。
WebSocket的長(zhǎng)連接,是一個(gè)真的全雙工,長(zhǎng)連接第一次tcp鏈路建立之后,后續(xù)數(shù)據(jù)可以雙方都進(jìn)行發(fā)送,不需要發(fā)送請(qǐng)求頭。

Spring中使用WebSocket

導(dǎo)入包

按照上面文章的代碼導(dǎo)入包的時(shí)候,發(fā)現(xiàn)前端連接后端的時(shí)候報(bào)錯(cuò),找了很多資料發(fā)現(xiàn)原因,tomcat 已有websocket,所以導(dǎo)致包沖突。


tomcat中的websocket包

所以在spring框架下應(yīng)該這樣導(dǎo)入包。

<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-websocket</artifactId>
     <version>5.3.0</version>
</dependency>
<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-messaging</artifactId>
     <version>5.3.0</version>
</dependency>

WebSocketConfig

@Configuration
public class WebSocketConfig {
    private static final long serialVersionUID = 7600559593733357846L;

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

websocketTest

@ServerEndpoint("/websocketTest/{username}")
@Component
public class WebSocketTest {
    private static int onlineCount = 0;
    private static ConcurrentHashMap<String, WebSocketTest> clients = new ConcurrentHashMap<String, WebSocketTest>();
    private Session session;
    private String username;

    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session) throws IOException {

        this.username = username;
        this.session = session;
        addOnlineCount();
        clients.put(username, this);
        System.out.println("已連接");
    }

    @OnClose
    public void onClose() throws IOException {
        clients.remove(username);
        subOnlineCount();
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println("收到客戶端的消息:" + message);
        sendMessageTo("已收到!", session);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    public void sendMessageTo(String message, Session session) throws IOException {
        for (WebSocketTest item : clients.values()) {
            if (item.session.equals(session))
                item.session.getAsyncRemote().sendText(message);
        }
    }

    public void sendMessageAll(String message) throws IOException {
        for (WebSocketTest item : clients.values()) {
            item.session.getAsyncRemote().sendText(message);
        }
    }

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

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

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

    public static synchronized ConcurrentHashMap<String, WebSocketTest> getClients() {
        return clients;
    }
}

結(jié)果展示

前端

服務(wù)端
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容