index.html 983 字节
Newer Older
1
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
2 3 4 5
<html>
<head>
</head>
<body>
6 7 8 9 10
<div id="time">只是接受消息的地方</div>
<input type="text" id="txtMsg"/>
<br/>
<button type="button" onclick="sendMsg()">发送消息</button>
<br/>
11
<script type="text/javascript">
12 13
    //new WebSocket
    var webSocket = new WebSocket("ws://localhost:8080/websocket");
14

15 16 17 18
    function sendMsg() {
        var txt = document.getElementById("txtMsg").value;
        console.log("待发送的消息是:" + txt);
        webSocket.send(txt);
19 20
    }

21 22
    webSocket.onopen = function () {
        console.log("连接成功");
23
    }
24 25
    webSocket.onclose = function () {
        console.log("连接关闭");
26
    }
27 28
    webSocket.onerror = function () {
        console.log("连接出错");
29
    }
30 31 32
    webSocket.onmessage = function (msg) {
        console.log("收到的消息是:" + msg.data);
        document.getElementById("time").innerHTML = msg.data;
33 34
    }
</script>
35 36
</body>
</html>