1. 程式人生 > >WebSocket javascript 客戶端

WebSocket javascript 客戶端

<!DOCTYPE html>
<html>
<head>
<title>websocket_test</title>
</head>
<body>
<div id="test">test websocket</div>
</body>
<script type="text/javascript">
    // 繫結點選事件
    document.getElementById("test").addEventListener('click', websocket_test);
    // websocket測試函式
    function websocket_test(){
        // 建立websocket物件
        var ws = new WebSocket("ws://127.0.0.1:8765");
        // open事件
        ws.onopen = function(){
            // 傳送訊息
            ws.send('hello!');
            console.log('send hello');
        }
        // message事件
        ws.onmessage = function(event){
            console.log(event.data);
            // 關閉連線
            ws.close();
        }
        // close事件
        ws.onclose = function(event){
            console.log('close');
        }
        // error事件
        ws.onerror = function(event){
            console.log('error');
        }
    }
</script>
</html>