<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>WebSocket Echo Client</title>
</head>
<body>
<div id="output">
</div>
</body>
<script>
//var output;
function setup(){
output = document.getElementById("output");
//new websocket
ws = new WebSocket("ws://echo.websocket.org/echo");
//监听器onopen,打开连接后执行
ws.onopen = function(e){
//连接打开
log("已经连接");
//调用sendMessage(e)方法
sendMessage("hello WebSocket!!");
}
//监听器onclose,关闭连接后执行
ws.onclose = function(e){
log("连接关闭:"+e.reason);
}
//监听器onerror,连接出错后执行
ws.onerror = function(e){
log("error");
}
//监听器onmessage,接收文本消息并显示消息内容的消息处理程序
ws.onmessage = function(e){
log("接收的信息:"+e.data);
//关闭连接
ws.close();
}
}
//发送信息的方法
function sendMessage(msg){
//发送信息
ws.send(msg);
log("消息已经发送!!");
}
//log方法,向浏览器输出信息
function log(s){
var p = document.createElement("p");
p.style.wordWrap = "break-word";
p.textContent = s;
output.appendChild(p);
console.log(s);
}
//执行setup()方法
setup();
</script>
</html>
执行结果:
已经连接
消息已经发送!!
接收的信息:hello WebSocket!!
连接关闭:
本文摘自《HTML5 WebSocket 权威指南》