websocket客户端实现

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
    <h1>Echo Test</h1>
    <input id="sendTxt" type="text">
    <button id="sendBtn" >发送</button>
    <div id="recv"></div>
    <script type="text/javascript">
        var websocket = new WebSocket("ws://echo.websocket.org/");
        websocket.onopen = function(){
            console.log('websocket open');
            document.getElementById('recv').innerHTML = "Connected";
        }
        websocket.onclose = function(){
            console.log('websocket close');
        }
        websocket.onmessage = function(e){
            console.log('e.data');
            document.getElementById('recv').innerHTML = e.data;
        }
        document.getElementById("sendBtn").onclick = function(){
            var txt = document.getElementById("sendTxt").value;
            websocket.send(txt);
        }
        
    </script>

</body>
</html>

 

posted on 2018-07-23 17:01  薇薇123456  阅读(210)  评论(0编辑  收藏  举报

导航