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

本文介绍了WebSocket的基本使用场景,以及为什么选择WebSocket替代HTTP长连接。在Spring中实现WebSocket,首先需要正确导入相关包,避免因Tomcat内置WebSocket造成的冲突。接着详细讲解了WebSocketConfig的配置、websocketTest的编写以及前端与后端如何建立一致的连接,最后展示了使用效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

前端

前端代码中尤其要注意url:('ws://localhost:8102/websocketTest/001'),需要和后端@ServerEndpoint("/websocketTest/{username}")保持一致。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Test</title>
</head>
<body>
<input id="text" type="text"/>
<button onclick="send()"> Send</button>
<button onclick="closeWebSocket()"> Close</button>
<div id="message"></div>

<script type="text/javascript">
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket('ws://localhost:8102/websocketTest/001');
        console.log("link success")
    } else {
        alert('Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function () {
        setMessageInnerHTML("error");
    };

    //连接成功建立的回调方法
    websocket.onopen = function (event) {
        setMessageInnerHTML("open");
    }

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        setMessageInnerHTML(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function () {
        setMessageInnerHTML("close");
    }

    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function () {
        websocket.close();
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //关闭连接
    function closeWebSocket() {
        websocket.close();
    }

    //发送消息
    function send() {
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>

</body>
</html>

结果展示

前端
服务端

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值