一个server-send events的小demo,后端用php实现
2012-08-03 16:43 vanillalyx 阅读(442) 评论(0) 编辑 收藏 举报<!DOCTYPE html> <html> <head> <title>server-sent event test</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" ></script> </head> <body> <p> Chat System </p> <ul id="chat_list"></ul> <label>Name</label> <input id="chat_name" /> <input id="chat_input" /> <button onclick="sendData()">发送</button> </body> <script type="text/javascript" > var bConnected = false; function sendData() { var name = document.getElementById("chat_name").value; if (!name) { return alert("plz input your name"); } if (!bConnected) { document.getElementById("chat_name").disabled = true; bConnected = true; connect(); } var data = document.getElementById("chat_input").value; if (data) { jQuery.ajax("chat.php?type=chat&data=" + escape(data) + "&name=" + escape(name), { cache: false, type: "GET", success: function(data) { }, error: function(xhr, errorstatus, errorthrow) { console.log(errorthrow); } }); } } function connect() { var name = document.getElementById("chat_name").value; if (!name) { return alert("plz input your name"); } var eventSrc = new EventSource('chat.php?type=eventResource&name=' + escape(name)); console.log("add event success"); eventSrc.addEventListener('open', function(event) { }); eventSrc.addEventListener('message', function(event) { if (event.type == "message") { var msg = document.createElement("li"); if(!event.data)return; msg.innerHTML = event.data; document.getElementById("chat_list").appendChild(msg); } }); }; </script> </html>
chat.html
<?php $filename = 'chat.txt'; if($_GET['type'] == 'chat'){ getMsg(); }else{ $msg = file_get_contents($filename); file_put_contents($filename, ''); $msg = $msg?$msg:''; dispatchMsg($msg); } function getMsg(){ $msg = $_GET['data']; file_put_contents('chat.txt', $msg); } function dispatchMsg($msg){ header("Content-Type:text/event-stream"); echo "data: " . $msg . "\r\n\r\n"; } ?>
chat.php
具体文章参考: http://www.fanjun.me/?tag=server-sent-events