美文网首页
Html5 Server-Sent

Html5 Server-Sent

作者: 星星编程 | 来源:发表于2017-05-02 17:59 被阅读60次
    <!DOCTYPE html>
    <html>
    <body>
    <h1>获得服务器更新</h1>
    <div id="result"></div>
    
    <script>
    if(typeof(EventSource)!=="undefined")
      {
      var source=new EventSource("/example/html5/demo_sse.php");
      source.onmessage=function(event)
        {
        document.getElementById("result").innerHTML+=event.data + "<br />";
        alert("提示有新的内容");
        this.location.reload(); 
        };
      }
    else
      {
      document.getElementById("result").innerHTML="抱歉,您的浏览器不支持 server-sent 事件 ...";
      }
    </script>
    
    </body>
    </html>
    

    php代码

    <?php
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');
    
    $time = date('r');
    echo "data: The server time is: {$time}\n\n";
    flush();
    ?>
    

    三种自动刷新页面的方法

    1.页面自动刷新:把如下代码加入<head>区域中 
    
    <meta http-equiv="refresh" content="20">,其中20指每隔20秒刷新一次页面. 
    
    2.页面自动跳转:把如下代码加入<head>区域中 
    
    <meta http-equiv="refresh" content="20;url=http://www.jb51.net">,其中20指隔20秒后跳转到http://www.jb51.net页面 
    
    3.页面自动刷新js版 
    
    <script language="JavaScript"> 
    function myrefresh(){ 
    window.location.reload(); 
    } 
    setTimeout('myrefresh()',1000); //指定1秒刷新一次 
    </script> 
    
    

    websocket

    <!DOCTYPE HTML>
    <html>
       <head>
       <meta charset="utf-8">
       <title>菜鸟教程(runoob.com)</title>
        
          <script type="text/javascript">
             function WebSocketTest()
             {
                if ("WebSocket" in window)
                {
                   alert("您的浏览器支持 WebSocket!");
                   
                   // 打开一个 web socket
                   var ws = new WebSocket("ws://localhost:9998/echo");
                    
                   ws.onopen = function()
                   {
                      // Web Socket 已连接上,使用 send() 方法发送数据
                      ws.send("发送数据");
                      alert("数据发送中...");
                   };
                    
                   ws.onmessage = function (evt) 
                   { 
                      var received_msg = evt.data;
                      alert("数据已接收...");
                   };
                    
                   ws.onclose = function()
                   { 
                      // 关闭 websocket
                      alert("连接已关闭..."); 
                   };
                }
                
                else
                {
                   // 浏览器不支持 WebSocket
                   alert("您的浏览器不支持 WebSocket!");
                }
             }
          </script>
            
       </head>
       <body>
       
          <div id="sse">
             <a href="javascript:WebSocketTest()">运行 WebSocket</a>
          </div>
          
       </body>
    </html>
    

    相关文章

      网友评论

          本文标题:Html5 Server-Sent

          本文链接:https://www.haomeiwen.com/subject/fvgtzttx.html