WebSocket&SSE实时动态数据展示

需求

  • 服务器主动推送数据给浏览器,实现数据实时更新展示

实现方式

  • WebSocket
  • SSE

SSE案例(Springboot项目)

  • maven依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
  • 创建一个controller
@RestController
@RequestMapping("/sse")
public class SseController {
    //SSE返回数据格式是固定的以data:开头,以\n\n结束
    @RequestMapping(value = "/get_data", produces = "text/event-stream;charset=UTF-8")
    public String push() throws InterruptedException {
        Thread.sleep(1000);
        return "data:测试数据:" + Math.random() + "\n\n";
    }
}
  • resource目录下创建public目录,然后创建index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <script type="text/javascript">
        // /sse/get_data
        let source = new EventSource("http://localhost:8080/sse/get_data");

        source.addEventListener('message',function (t){
            var data = t.data;
            document.getElementById("result").innerText = data;
        })
        source.addEventListener('open', function(e) {
            console.log("连接打开.");
        }, false);
        source.addEventListener('error', function(e) {
            if (e.readyState == EventSource.CLOSED) {
                console.log("连接关闭");
            } else {
                console.log(e.readyState);
            }
        }, false);
        
    </script>
</head>
<body>
    模拟数据:
        <div>测试</div>
        <div id="result"></div>
</body>
</html>
  • 创建Application启动类,启动项目
  • 浏览器访问: localhost:8080/index.html

WebSocket案例(Springboot项目)

  • maven依赖
  <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--websocket -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
    </dependencies>
  • 创建config包,创建WebSocketConfig.java
/**
 * 开启WebSocket支持
 */
@Configuration
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    /**
     * 扫描@ServerEndpoint,将@ServerEndpoint修饰的类注册为websocket
     * 如果使用外置tomcat,则不需要此配置
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
  • 创建server包,创建MysqlSocketServer.java MysqlUtil.java User.java
@ServerEndpoint("/wsMysql")
@Component
public class MysqlSocketServer {

    private static final ScheduledExecutorService executor = Executors.newScheduledThreadPool(3);

    @OnOpen
    public void onOpen(Session session) throws IOException {
        System.out.println(String.format("Socket Connection  onOpen ....%s",Thread.currentThread().getId()));
        executor.scheduleAtFixedRate(() -> {
            try {
                MysqlUtil.pushLog(session);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, 2, 1, TimeUnit.SECONDS);

    }

    @OnClose
    public void onClose(Session session) {
        System.out.println(String.format("Socket Connection onClose ..... %s",Thread.currentThread().getId()));
    }

    @OnError
    public void onError(Throwable e) {

        System.out.println("Socket Connection onError .....");
        e.printStackTrace();
    }

}
@Configuration
@EnableScheduling
public class MysqlUtil {

    public static List<User> users = new ArrayList<>();

    public static void pushLog(Session session) throws IOException {
        //查询数据:
        List<User> users = findAll();
        session.getBasicRemote().sendText(JSON.toJSONString(users));

    }

    private static List<User> findAll() {
        return users;
    }

    static {
        int num = (int) (1 + Math.random() * (3 - 1 + 1));
        users.add(new User("1", "tom", 12));
        users.add(new User("2", "jim", 22));
        users.add(new User("3", "jack", 32));

        ArrayList<User> rs = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            rs.add(users.get(i));
        }

    }


    @Scheduled(fixedRate = 2000)
    public void configureTasks() throws IOException {
        int num = (int) Math.random();
        users.add(new User(String.valueOf(num), "name" + num, num * 2));
    }



}

public class User {
    private String id;
    private String name;
    private Integer age;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public User(String id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
}

  • resources目录下创建static目录,创建index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>mysql中获取数据,实时展示</title>
</head>
<body>

<div id="logContainer" >

</div>

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        if (typeof (WebSocket) == "undefined") {
            console.log("您使用的浏览器不支持WebSocket");
        } else {
            //连接到websocket端点,测试服、正式服环境要写应用所在机器的具体域名|ip
            let socket = new WebSocket("ws://127.0.0.1:7500/wsMysql");
            socket.onopen = () => {
                console.log("已连接到wsServer");
            };
            socket.onclose = () => {
                console.log("已断开与wsServer的连接");
            };
            socket.onerror = (e) => {
                console.log("发生错误", e);
            }
            socket.onmessage = function (event) {
                console.log("接收到的数据:" + event.data);
                document.getElementById("logContainer").innerText = event.data
            };
        }
    });
</script>

</body>
</html>

  • 创建application.yml
server:
  port: 7500
  • 启动服务,访问 localhost:7500/index.html
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值