【Java基础】WebSocket在Spring中的使用

2021-03-05  本文已影响0人  Tcpieg

WebSocket

使用

关于怎么使用WebSocket,以及WebSocket的一些概念,这篇文章有做详细的介绍。

为什么要使用WebSocket

我接触到WebSocket,是因为想使用WebSocket来替代HTTP 长连接。

HTTP1.1通过使用Connection:keep-alive进行长连接,HTTP 1.1默认进行持久连接,在一次 TCP 连接中可以完成多个 HTTP 请求,但是对每个请求仍然要单独发 header,Keep-Alive不会永久保持连接,它有一个保持时间,可以在不同的服务器软件(如Apache)中设定这个时间,这种长连接是一种“伪链接”。
WebSocket的长连接,是一个真的全双工,长连接第一次tcp链路建立之后,后续数据可以双方都进行发送,不需要发送请求头。

Spring中使用WebSocket

导入包

按照上面文章的代码导入包的时候,发现前端连接后端的时候报错,找了很多资料发现原因,tomcat 已有websocket,所以导致包冲突。


tomcat中的websocket包

所以在spring框架下应该这样导入包。

<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;
    }
}

结果展示

前端
服务端
上一篇下一篇

猜你喜欢

热点阅读