SpringBoot+WebSocket技术实现

WebSocket

1.背景

为了实现推送技术,实时更新前端页面。

2.实现方式

1.Ajax 轮询。轮询是在特定的的时间间隔(如每1秒),由浏览器对服务器发出HTTP请求,然后由服务器返回最新的数据给客户端的浏览器

2.浏览器通过 JavaScript 向服务器发出建立 WebSocket 连接的请求,连接建立以后,客户端和服务器端就可以通过 TCP 连接直接交换数据。

在这里插入图片描述

3.优势

Ajax:这种传统的模式带来很明显的缺点,即浏览器需要不断的向服务器发出请求,然而HTTP请求可能包含较长的头部,其中真正有效的数据可能只是很小的一部分,显然这样会浪费很多的带宽等资源。

webSocket:HTML5 定义的 WebSocket 协议,能更好的节省服务器资源和带宽,并且能够更实时地进行通讯。

4.SpringBoot整合webSocket 的DEMO

源码git地址:https://gitee.com/x_p_fei/boot-web-socket.git

1.引入依赖pom.xml

<!--websocket连接需要使用到的包-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2.注入ServerEndpointExporter

新建文件WebSocketConfig.java
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
    return new ServerEndpointExporter();
}

3.webSocket服务文件

package cn.sr.nrsd.webSocket.socket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

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

@Slf4j
@ServerEndpoint("/websocket")
@Component
public class WebSocketController {
    private static int onlineCount = 0;
    private static CopyOnWriteArrayList<WebSocketController> webSocketSet = new CopyOnWriteArrayList<WebSocketController>();
    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);//加入set中
        addOnlineCount();
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        subOnlineCount();
        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
//        群发消息
        try {
            sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("发生错误!");
        throwable.printStackTrace();
    }

    //   下面是自定义的一些方法
    public void sendMessage(String message) throws IOException {
        for (WebSocketController webSocketController : webSocketSet) {
            try {
                Session toSession = webSocketController.session;
                if (toSession.isOpen()) {
                    log.info("服务端给客户端[{}]发送消息{}", toSession.getId(), message);
                    toSession.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }

        }
    }

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

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

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

4.添加静态页面

在项目resources下面新建文件 static, 在static文件中添加静态页面index.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Java后端WebSocket的Tomcat实现</title>
</head>
<body>
Welcome<br/><input id="text" type="text"/>
<button onclick="send()">发送消息</button>
<hr/>
<button onclick="closeWebSocket()">关闭WebSocket连接</button>
<hr/>
<div id="message"></div>
</body>

<script type="text/javascript">
    var websocket = null;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
          //注意修改端口号
        websocket = new WebSocket('ws://localhost:7001/websocket');
    }
    else {
        alert('当前浏览器 Not support websocket')
    }

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

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

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

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

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

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

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

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

5.启动失败原因

AOP日志切面,切到了webSocket服务,导致@ServerEndpoint没有注入,启动报错。注意修改切面日志或者包名,不要被AOP扫描到。 ——>启动成功

6.启动项目

访问 localhost:7001/,会跳转到 index 页面。然后可以进行发消息操作。

点击发消息,前端先把消息传到服务器,之后服务器处理后再发送给前端。服务器也可以直接发送消息到前端页面。至此就实现了后端服务器推送技术。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值