webSocket实现网站消息实时推送(仅前端)

需求: 小程序端有司机外发接单,后台管理系统实时消息接收

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<link th:src="@{css/bootstrap.min.css}" rel="stylesheet">
<script th:src="@{js/sockjs.min.js}"></script>
<script th:src="@{js/stomp.js}"></script>
<script th:src="@{js/jquery-3.1.1.js}"></script>
<head>
    <title>车队端</title>
</head>
<body>

<div id="main-content" class="container">
    <div class="row">
        <div class="col-md-6">
            <form class="form-inline">
                <div class="form-group">
                    <label for="connect">WebSocket connection11:</label>
                    <button id="connect" class="btn btn-default" type="submit">Connect</button>
                    <button id="disconnect" class="btn btn-default" type="submit" disabled="disabled">Disconnect
                    </button>
                    <input type="text" id="login" class="form-control" placeholder="login编码">
                </div>
            </form>
        </div>
        <div class="col-md-6">
            <form class="form-inline">
                <div class="form-group">
                    <label for="name">What is your name?</label>
                    <input type="text" id="name" class="form-control" placeholder="Your name here...">
                </div>
                <button id="send" class="btn btn-default" type="submit">Send</button>
            </form>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <table id="conversation" class="table table-striped">
                <thead>
                <tr>
                    <th>你有新消息啦</th>
                </tr>
                </thead>
                <tbody id="greetings">
                </tbody>
            </table>
        </div>
    </div>
    </form>
</div>

<script>
    //  /msg/sendcommuser
    var socket;
    var stompClient = null;
    //传递用户key值
    var login = "";
    function setConnected(connected) {
        $("#connect").prop("disabled", connected);
        $("#disconnect").prop("disabled", !connected);
        if (connected) {
            $("#conversation").show();
        }
        else {
            $("#conversation").hide();
        }
        $("#greetings").html("");
    }

    function connect() {
        //建立连接对象
        socket = new SockJS('http://192.168.1.122:8080/ricky-websocket');
        sockHandle(); //类似于生命周期钩子(个人理解)
        login=$("#login").val();
        // 获取stomp子协议的客户端对象
        stompClient = Stomp.over(socket);
        // 定义客户端的认证信息,按需求配置
        // let header = {
        //   Authorization:''
        // }
        //向服务器端发起websocket连接
        stompClient.connect({flag:9}, function (frame) {
            setConnected(true);
            console.log('Connected: ' + frame);
            stompClient.subscribe('/user/topic/erpFinancialAudit', function (greeting) {//订阅服务端提供的某个topic
                console.log("有没有订阅成功"+greeting);  //greeting.body存放的是服务端发送给我们的信息
                showGreeting(greeting);
            });
        },(err) => {
            // 连接发生错误时的处理函数
            console.log('失败')
            console.log(err);
        });
    }
    //连接错误时调用
    function disconnect() {
        if (stompClient != null) {
            stompClient.disconnect();
        }
        setConnected(false);
        console.log("Disconnected");
    }
    // 显示返回的信息
    function showGreeting(message) {
        $("#greetings").append("<tr><td>" + message + "</td></tr>");
    }
    // 类似socket的连接的生命周期
    function sockHandle() {
        socket.onopen = function () {
            console.log("------连接成功------");
        };
        socket.onmessage = function (event) {
            console.log('-------Received: ' + event.data);
        };
        socket.onclose = function (event) {
            console.log('--------Info: connection closed.------');
        };
        //连接发生错误
        socket.onerror = function () {
            alert("连接错误", "网络超时或通讯地址错误.");
            disconnect();
        };
    }
    // 发送信息
    function sendName() {
        stompClient.send("/app/msg/hellosingle", {}, JSON.stringify({'name': $("#name").val(),'id':login}));
    }

    $(function () {
        $("form").on('submit', function (e) {
            e.preventDefault();
        });
        $( "#connect" ).click(function() { connect(); });
        $( "#disconnect" ).click(function() { disconnect(); });
        $( "#send" ).click(function() { sendName(); });
    });
</script>
</body>
</html>
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值