HTML5提供了许多新接口,其中最令人振奋的无疑是Websocket。正是它的存在令网络双向交互得以实现。
使用Websocket对于客户端来说无疑十分简单。websocket提供了三个简单的函数,onopen,onclose以及onmessage,顾名思义,他们分别监听socket的开启、断开和消息状态。
例如在一个WebSocket的客户端例子中,你可以这样写:
< !DOCTYPE html>
< html xmlns=”http://www.w3.org/1999/xhtml”>
< title>Web Socket Example
< meta charset=”UTF-8″>
< script>
window.onload = function() {
var s = new WebSocket(“ws://localhost:8000/”);
s.onopen = function(e) { alert(“opened”); }
s.onclose = function(e) { alert(“closed”); }
s.onmessage = function(e) { alert(“got: ” + e.data); }
};
< /script>
< /head>
< body>
< div id=”holder” style=”width:600px; height:300px”>