建立一个社交网络,我正在尝试获取实时通知。当前,站点使用setInterval每隔几秒钟发送一次AJAX请求。看起来像这样:
setInterval ( function(){ url = base_dir+"/ajax/file.php"; data = "data=someData"; $.ajax({ type: "POST", url: url, data: data, dataType: "json", beforeSend: function(x) { if(x && x.overrideMimeType) { x.overrideMimeType("application/json;charset=UTF-8"); } }, success: function(JSON){ // retrieve data here } }); }, 5000);
那很好,但是我非常担心创建服务器过载。我尝试了彗星技术,但由于某种原因,它发送的请求比上述代码多得多。还有其他更有用的技术来实时发布此数据吗?
编辑:为实现长轮询,我使用了以下内容(使用此处提到的示例:http : //techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and- jquery):
(function poll(){ url = base_dir+"/ajax/file.php"; data = "data=someData"; $.ajax({ type: "POST", url: url, data: data, dataType: "json", beforeSend: function(x) { if(x && x.overrideMimeType) { x.overrideMimeType("application/json;charset=UTF-8"); } }, success: function(JSON){ // retrieve data here }, complete: poll, timeout: 5000 }); })();
我有可能无法正确理解彗星原理。
PHP代码:
// Checks for new notifications, and updates the title and notifications bar if there are any private static function NotificationsCounter (){ //self::$it_user_id = query that retrieves my id for further checks; //$friend_requests_count = query that retrieves the friend requests count; //$updates_count = query that retrieves the updates count; $total_notifications = $friend_requests_count+$updates_count; if ($total_notifications > 0) $addToTitle = "(".$total_notifications.")"; else $addToTitle = ""; if ($updates_count > 0) $counterHTML = "<span class='notification_counter' id='updates_counter' style='float: right;'>".$updates_count."</span>"; else $counterHTML = ""; $data = array("counter"=>$total_notifications,"addToTitle"=>$addToTitle,"counterHTML"=>$counterHTML,); echo json_encode($data); // parse to json and print }
由于Facebook也使用PHP,因此该怎么做?
您应该使用 websockets 。您可以连接到服务器并注册onmessage处理程序。只要服务器有任何要发送给客户端的内容,处理程序都会被调用。无需超时。
在浏览器中检查websocket支持。到目前为止,仅Chrome,Opera和Safari支持它们。
if ('WebSocket' in window){ /* WebSocket is supported. You can proceed with your code*/ } else { /*WebSockets are not supported. Try a fallback method like long-polling etc*/ }
连接中
var connection = new WebSocket('ws://example.org:12345/myapp');
处理程序
connection.onopen = function(){ console.log('Connection open!'); } connection.onclose = function(){ console.log('Connection closed'); } connection.onmessage = function(e){ var server_message = e.data; console.log(server_message); }
文档:http : //www.developerfusion.com/article/143158/an-introduction-to- websockets/