如何实现推送是客户端有发送数据到服务器时,然后推送给客户端。firebug网络中一直有get请求,会不会浪费资源呢

解决方案 »

  1.   

    <!doctype html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title>basic SSE test</title>
            <script type="text/javascript" src="jquery.1.4.2-min.js"></script>
        </head>
        <body>
            <pre id = "x">initializting...<?php echo 'now time is '.date('r');?></pre>
            <!--之所以使用pre标签而不是p或者div是为了确保数据能以它被接受时的格式呈现,而不会修改或格式化-->
            <textarea class="log" style="width: 100%; height: 500px;">
            </textarea>
            <input type="text" id="text">
            <input type="button" value="发送" onClick="send()">
            <input type="button" value="清屏" onClick="Clear()">
        </body>
        <script>
            var es = new EventSource("basic_sse.php");
            es.addEventListener("message",function(e){
                if(e.data != ''){
                document.getElementById("x").innerHTML += "\n"+e.data;
                }
            },false);//使用false表示在冒泡阶段处理事件,而不是捕获阶段。
            function send(){
             var text=$('#text').val();
             if(text!=''){
             $('.log').append(text+"\r\n");
             $.ajax({
             type:'POST',
             async:false,
             url:'basic_sse.php',
             data:'mess='+text,
             success:function(msg){
             
               },
               error:function(){
                 alert('发送失败服务器响应超时');
                  }
                })
             }
            }
            function Clear(){
             $('.log').html('');
             $('#text').attr('value','');
            }
        </script>
    </html>
      

  2.   

    <?php
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');
        $time = date('r');
        $con=mysqli_connect('localhost','root','root','test') or die(mysql_error());
        mysqli_query($con,"SET names UTF8") or die(mysql_error());
        if(isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"])=="xmlhttprequest"){
          $mess=$_POST['mess'];
          $time=date('Y-m-d H:i:s');
          $sql='insert into messages (content,time) values ("'.$mess.'","'.$time.'")';
          if(mysqli_query($con,$sql)){
            $_SESSION['data'] = $mess;
            exit;
          }
        }
        echo "data: ".$_SESSION['data']."\n\n";
        
        flush();
    ?>
      

  3.   

    如果是 服务器推送,那么一定是用的 WebSocket 协议通讯
    但在你的代码中并未看到 ws:// 字样(因为网站默认是 http 协议通讯,所以 WebSocket 协议类型声明不可缺省)