虽然长连接这个东西已经被广泛使用,但是真的想要了解是什么样子的时候,相关的DEMO却很少,所以本人觉得有必要记录一下
html+JS:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>sokit demo</title> <link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css"/> <style type="text/css"> .msg-container{ height: 300px; overflow-y: scroll; overflow-x: hidden; padding-top: 50px;} .msg-item{padding: 15px; line-height: 1.5em;} .msg-item.right{ background: #;} .msg-item.label{ display: inline-block;} </style> </head> <body> <div class="container"> <div class="text-center">hello mackes</div> <div class="msg-container"> <div class="col-xs-12 form-group"> <div class="col-md-8"> <div class="msg-item left label label-info"> 你好,可爱的小家伙 </div> </div> </div> <div class="col-xs-12 form-group"> <div class="col-md-8 col-md-offset-4 text-right"> <div class="msg-item right label label-warning"> 你好,可爱的小家伙 </div> </div> </div> <div class="col-xs-12 form-group"> <div class="col-md-8 col-md-offset-4 text-right"> <div class="msg-item right label label-warning"> 你好,可爱的小家伙 </div> </div> </div> </div> <div> <input type="text" id="msg" class="form-control" value="" placeholder="请输入聊天信息" /> </div> <div class="text-center"><button class="btn btn-success btn-block">SEND</button></div> </div> <!--<script src="https://cdn.bootcss.com/socket.io/2.0.3/socket.io.js" type="text/javascript" charset="utf-8"></script>--> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> var es = new EventSource('msg.php'); es.onmessage = function (e) { console.log(e.data); // 然后做点什么.. html= '<div class="col-xs-12 form-group">'+ '<div class="col-md-8 col-md-offset-4 text-right">'+ '<div class="msg-item right label label-warning">'+ e.data+ '</div>'+ '</div>'+ '</div>'; $('.msg-container').append(html); }; </script> </body> </html>
msg.php
<?php header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); $time = date('r'); echo "data: hello \n\n"; flush(); ?>
搭起来看一下你就明白了,后端注意关键的两点:
1、header('Content-Type: text/event-stream');
2、echo “data: xxxxxx \n\n”; 这个格式