| 1 |
<!DOCTYPE HTML> |
| 2 |
<html> |
| 3 |
|
| 4 |
<head> |
| 5 |
<meta charset="utf-8"> |
| 6 |
<title>WebSocket客户端</title> |
| 7 |
|
| 8 |
<script type="text/javascript"> |
| 9 |
function WebSocketTest(url) |
| 10 |
{ |
| 11 |
if ("WebSocket" in window) |
| 12 |
{ |
| 13 |
// 打开一个 web socket |
| 14 |
var ws = new WebSocket(url); |
| 15 |
|
| 16 |
ws.onopen = function() |
| 17 |
{ |
| 18 |
alert("连接已建立"); |
| 19 |
ws.send("hello"); |
| 20 |
}; |
| 21 |
|
| 22 |
ws.onmessage = function(ev) |
| 23 |
{ |
| 24 |
var received_msg = ev.data; |
| 25 |
console.log("received websocket message: " + received_msg); |
| 26 |
var li=document.createElement("li"); |
| 27 |
li.innerHTML=received_msg; |
| 28 |
document.getElementById("msg_list").appendChild(li); |
| 29 |
}; |
| 30 |
|
| 31 |
ws.onclose = function() |
| 32 |
{ |
| 33 |
alert("连接已关闭"); |
| 34 |
}; |
| 35 |
} |
| 36 |
else |
| 37 |
{ |
| 38 |
alert("您的浏览器不支持 WebSocket!"); |
| 39 |
} |
| 40 |
} |
| 41 |
</script> |
| 42 |
</head> |
| 43 |
|
| 44 |
<body> |
| 45 |
URL: <input type="text" id="url" value="ws://127.0.0.1:9999/test" style="width:300px;"> |
| 46 |
<button onclick="WebSocketTest(document.getElementById('url').value)">运行 WebSocket</button> |
| 47 |
<div> |
| 48 |
<ul id="msg_list" style="height:500px;overflow-y:scroll;"> |
| 49 |
</ul> |
| 50 |
<div> |
| 51 |
</body> |
| 52 |
|
| 53 |
</html> |