2018年8月11日

Websocket 简单 demo

websocket,可以在浏览器和服务器之间建立一个全双工通信的 socket 连接。它与 http 请求的主要区别在于,可以由服务器主动向客户端推送消息。

以下是一个简单 demo:

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

“以书为舟,遨游尘世”,
最好的免费 kindle 电子书分享站:

You may also like...

发表回复

您的电子邮箱地址不会被公开。


*