WebSocket

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html>
 3 <head>
 4     <title>HTTP Polling</title>
 5     <script type="text/javascript" src="/js/jquery-1.4.4.min.js"></script>
 6     <script type="text/javascript">
 7         var num = 0;
 8         jQuery(function ($) {
 9             function long_polling() {
10                 //$('#logs').append("Waiting...<br/>");
11                 $.get('comet.asyn?num=' + num + "&r=" + Math.random(), function (d) {
12                     if (d) {
13                         eval("data=" + d);
14                         $('#logs').append(data.UpdateMillisec + "<br/>");
15                         num = data.count;
16                     }
17                     long_polling();
18                 });
19             }
20             long_polling();
21         });
22     </script>
23 </head>
24 <body>
25     <div id="logs" style="font-family: monospace;">
26     </div>
27 </body>
28 </html>
Comet.html
 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <title></title>
 5 </head>
 6 <body>
 7     <div id="socket">
 8     </div>
 9     <script type="text/javascript">
10         var o = document.getElementById("socket");
11         // 创建一个Socket实例
12         var socket = new WebSocket('ws://10.10.10.1:8050/');
13 
14         // 打开Socket
15         socket.onopen = function (event) {
16 
17             // 发送一个初始化消息
18             socket.send('I am the client and I\'m listening!');
19 
20             // 监听消息
21             socket.onmessage = function (event) {
22                 console.log('Client received a message', event);
23                 o.innerHTML += "Client received a message:<br/>" + event;
24             };
25 
26             // 监听Socket的关闭
27             socket.onclose = function (event) {
28                 console.log('Client notified socket has closed', event);
29             };
30 
31             // 关闭Socket.... 
32             //socket.close() 
33         };
34     </script>
35 </body>
36 </html>
Socket.html

WebSocket

posted on 2013-12-10 11:32  davidkam  阅读(250)  评论(0编辑  收藏  举报