webScoket(angular.js、vue.js )分别实现,实时接收后台发送过来的数据信息!转载(已测试通过)

15 篇文章 0 订阅
VUE.js实现    angular.js    http://www.cnblogs.com/goodhelper(这个人博客很厉害,可以关注)
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>My WebSocket</title>
    <script src="https://cdn.bootcss.com/vue/2.5.10/vue.js"></script>
</head>
<body>
Welcome To My WebSocket.<br/><br/>
<div id="ws">
    <input id="text" type="text"/>
    <button οnclick="sendMsg()">Send</button>
    <button οnclick="closeWS()" :disabled="!opened">Close</button>
    <button οnclick="openWS()" :disabled="opened">Open</button>
    <div v-html="msg"></div>
</div>
</body>
<script type="text/javascript">

    var websocket = null;

    var wsVue = new Vue({
        el: '#ws',
        data: {
            msg: "welcome to my websocket...<br/>",
            opened: false
        },
        mounted: function () {
            initWs();
        }
    });

    function initWs() {
        //check if your browser supports WebSocket
        if ('WebSocket' in window) {
            websocket = new WebSocket("ws://(服务端的地址,且支持跨域,不需要添加http://,只需要:端口:例如:192.168.1.73:10101)/my-websocket");
        }
        else {
            alert('Sorry, websocket not supported by your browser.')
        }

        //Error callback
        websocket.onerror = function () {
            setMessageContent("error!");
            wsVue.opened = false;
        };

        //socket opened callback
        websocket.onopen = function (event) {
            setMessageContent("websocket opened");
            wsVue.opened = true;
        }

        //message received callback
        websocket.onmessage = function (event) {
            setMessageContent(event.data);
        }

        //socket closed callback
        websocket.onclose = function () {
            setMessageContent("websocket closed");
            wsVue.opened = false;
        }

        //when browser window closed, close the socket, to prevent server exception
        window.onbeforeunload = function () {
            websocket.close();
        }
    }

    //update message to vue and then in div
    function setMessageContent(content) {
        wsVue.msg += content + '<br/>';
    }

    //click to close the websocket
    function closeWS() {
        websocket.close();
        wsVue.opened = false;
    }

    //click to open the websocket
    function openWS() {
        initWs();
    }

    //click to send message
    function sendMsg() {
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>
</html>

 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值