- 浏览: 1522807 次
- 性别:
- 来自: 厦门
文章分类
- 全部博客 (516)
- Java (49)
- Java/Struts 2.0 (25)
- Java/Spring、Spring MVC (11)
- Java/Quartz (3)
- Java/Lucene (6)
- Java/Hibernate (19)
- Java/openJPA (7)
- Java/DWR (7)
- Java/Security、Spring Security/OAuth2 (6)
- Java/Threading (9)
- Java/XML (22)
- java/design pattern (4)
- Android (2)
- JavaScript (46)
- jquery (3)
- DB/MySQL (23)
- DB/Oracle (16)
- PHP (25)
- CSS (20)
- Linux (38)
- C/C++、DLL、Makefile、VC++ (31)
- 正则 (9)
- Eclipse (4)
- 安全、网络等概念 (25)
- 集群 (7)
- 网页 (5)
- 视频\音频 (1)
- HTML (6)
- 计算机数学/算法 (3)
- Virtualbox (1)
- LDAP (2)
- 数据挖掘 (6)
- 工具破解 (1)
- 其他 (13)
- Mail (1)
- 药材 (3)
- 游戏 (2)
- hadoop (13)
- 压力测试 (3)
- 设计模式 (3)
- java/Swing (2)
- 缓存/Memcache (0)
- 缓存/Redis (1)
- OSGI (2)
- OSGI/Gemini (0)
- 文档写作 (0)
- java/Servlet (3)
- MQ/RabbitMQ (2)
- MQ/RocketMQ (0)
- MQ/Kafka (1)
- maven (0)
- SYS/linux (1)
- cache/redis (1)
- DB/Mongodb (2)
- nginx (1)
- postman (1)
- 操作系统/ubuntu (1)
- golang (1)
- dubbo (1)
- 技术管理岗位 (0)
- mybatis-plus (0)
最新评论
-
pgx89112:
大神,请赐我一份这个示例的项目代码吧,万分感谢,1530259 ...
spring的rabbitmq配置 -
string2020:
不使用增强器 怎么弄?
OpenJPA的增强器 -
孟江波:
学习了,楼主,能否提供一份源代码啊,学习一下,十分感谢!!!4 ...
spring的rabbitmq配置 -
eachgray:
...
spring-data-redis配置事务 -
qljoeli:
学习了,楼主,能否提供一份源代码啊,学习一下,十分感谢!!!1 ...
spring的rabbitmq配置
http://www.zeitoun.net/articles/comet_and_php/start
Comet is a programming technique that enables web servers to send data to the client without having any need for the client to request it. This technique will produce more responsive applications than classic AJAX. In classic AJAX applications, web browser (client) cannot be notified in real time that the server data model has changed. The user must create a request (for example by clicking on a link) or a periodic AJAX request must happen in order to get new data fro the server.
I will now explain how to implement Comet with PHP programming language. I will demonstrate it on two demos which uses two techniques: the first one is based on hidden ”<iframe>” and the second one is based on classic AJAX non-returning request. The first demo will simply show the server date in real time on the clients and the second demo will display a mini-chat.
Comet with iframe technique : server timestamp demo
We need:
*
A PHP script that will handle the persistent http request (backend.php)
*
A HTML file that will load Javascript code and that will show the data coming from the server (index.html)
*
The prototype library that will help us to write simple JS code
To understand how it works this schema should help:
The backend script (PHP)
This script will do an infinite loop and will return the server time as long as the client is connected. Call it “backend.php”:
<?php header("Cache-Control: no-cache, must-revalidate"); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); flush(); ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Comet php backend</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <script type="text/javascript"> // KHTML browser don't share javascripts between iframes var is_khtml = navigator.appName.match("Konqueror") || navigator.appVersion.match("KHTML"); if (is_khtml) { var prototypejs = document.createElement('script'); prototypejs.setAttribute('type','text/javascript'); prototypejs.setAttribute('src','prototype.js'); var head = document.getElementsByTagName('head'); head[0].appendChild(prototypejs); } // load the comet object var comet = window.parent.comet; </script> <?php while(1) { echo '<script type="text/javascript">'; echo 'comet.printServerTime('.time().');'; echo '</script>'; flush(); // used to send the echoed data to the client sleep(1); // a little break to unload the server CPU } ?> </body> </html>
The client script (HTML)
This HTML document first load the prototype library in the ”<head>” tag, then it create the tag that will contains the server timer ”<div id=“content”></div>”, and finally it create a “comet” javascript object that will connect the backend script to the time container tag.
The comet object will create some invisible “iframe” tags (depends on the web browser). These iframes are in charge to create the background persistent http connection with the backend script. Notice: this script do not handle possible connection problems between client and server.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Comet demo</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="prototype.js"></script> </head> <body> <div id="content">The server time will be shown here</div> <script type="text/javascript"> var comet = { connection : false, iframediv : false, initialize: function() { if (navigator.appVersion.indexOf("MSIE") != -1) { // For IE browsers comet.connection = new ActiveXObject("htmlfile"); comet.connection.open(); comet.connection.write("<html>"); comet.connection.write("<script>document.domain = '"+document.domain+"'"); comet.connection.write("</html>"); comet.connection.close(); comet.iframediv = comet.connection.createElement("div"); comet.connection.appendChild(comet.iframediv); comet.connection.parentWindow.comet = comet; comet.iframediv.innerHTML = "<iframe id='comet_iframe' src='./backend.php'></iframe>"; } else if (navigator.appVersion.indexOf("KHTML") != -1) { // for KHTML browsers comet.connection = document.createElement('iframe'); comet.connection.setAttribute('id', 'comet_iframe'); comet.connection.setAttribute('src', './backend.php'); with (comet.connection.style) { position = "absolute"; left = top = "-100px"; height = width = "1px"; visibility = "hidden"; } document.body.appendChild(comet.connection); } else { // For other browser (Firefox...) comet.connection = document.createElement('iframe'); comet.connection.setAttribute('id', 'comet_iframe'); with (comet.connection.style) { left = top = "-100px"; height = width = "1px"; visibility = "hidden"; display = 'none'; } comet.iframediv = document.createElement('iframe'); comet.iframediv.setAttribute('src', './backend.php'); comet.connection.appendChild(comet.iframediv); document.body.appendChild(comet.connection); } }, // this function will be called from backend.php printServerTime: function (time) { $('content').innerHTML = time; }, onUnload: function() { if (comet.connection) { comet.connection = false; // release the iframe to prevent problems with IE when reloading the page } } } Event.observe(window, "load", comet.initialize); Event.observe(window, "unload", comet.onUnload); </script> </body> </html>
Comet with classic AJAX : litte chat demo
As on the above technique, we need:
*
A file to exchange data (data.txt)
*
A PHP script that will handle the persistent http request (backend.php)
*
A HTML file that will load Javascript code and that will show the data coming from the server (index.html)
*
The prototype library that will help us to write simple JS code
The backend script (PHP)
This script will do two things:
*
Write into “data.txt” when new messages are sent
*
Do an infinite loop as long as “data.txt” file is unchanged
<?php $filename = dirname(__FILE__).'/data.txt'; // store new message in the file $msg = isset($_GET['msg']) ? $_GET['msg'] : ''; if ($msg != '') { file_put_contents($filename,$msg); die(); } // infinite loop until the data file is not modified $lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0; $currentmodif = filemtime($filename); while ($currentmodif <= $lastmodif) // check if the data file has been modified { usleep(10000); // sleep 10ms to unload the CPU clearstatcache(); $currentmodif = filemtime($filename); } // return a json array $response = array(); $response['msg'] = file_get_contents($filename); $response['timestamp'] = $currentmodif; echo json_encode($response); flush(); ?>
The client script (HTML)
This HTML document first load the prototype library in the ”<head>” tag, then it create the tag ”<div id=“content”></div>” that will contains the chat messages comming from “data.txt” file, and finally it create a “comet” javascript object that will call the backend script in order to watch for new chat messages.
The comet object will send AJAX requests each time a new message has been received and each time a new message is posted. The persistent connection is only used to watch for new messages. A timestamp url parameter is used to identify the last requested message, so that the server will return only when the “data.txt” timestamp is newer that the client timestamp.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Comet demo</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="prototype.js"></script> </head> <body> <div id="content"> </div> <p> <form action="" method="get" onsubmit="comet.doRequest($('word').value);$('word').value='';return false;"> <input type="text" name="word" id="word" value="" /> <input type="submit" name="submit" value="Send" /> </form> </p> <script type="text/javascript"> var Comet = Class.create(); Comet.prototype = { timestamp: 0, url: './backend.php', noerror: true, initialize: function() { }, connect: function() { this.ajax = new Ajax.Request(this.url, { method: 'get', parameters: { 'timestamp' : this.timestamp }, onSuccess: function(transport) { // handle the server response var response = transport.responseText.evalJSON(); this.comet.timestamp = response['timestamp']; this.comet.handleResponse(response); this.comet.noerror = true; }, onComplete: function(transport) { // send a new ajax request when this request is finished if (!this.comet.noerror) // if a connection problem occurs, try to reconnect each 5 seconds setTimeout(function(){ comet.connect() }, 5000); else this.comet.connect(); this.comet.noerror = false; } }); this.ajax.comet = this; }, disconnect: function() { }, handleResponse: function(response) { $('content').innerHTML += '<div>' + response['msg'] + '</div>'; }, doRequest: function(request) { new Ajax.Request(this.url, { method: 'get', parameters: { 'msg' : request }); } } var comet = new Comet(); comet.connect(); </script> </body> </html>
发表评论
-
mysql_query()防止掉链的数据库查询
2011-03-24 14:00 1728// ---------------------------- ... -
Windows下的Memcache安装
2011-03-22 10:06 2106转自:http://www.ccvita.com/258.ht ... -
PHP 解决采集乱码问题mb_convert_encoding和iconv使用比较
2011-02-11 13:27 3002转自:http://hi.baidu.com/ ... -
采集数据
2011-01-28 17:27 921<? // 连接数据库的配置 $config = a ... -
eclipse xdebug 配置手册
2010-10-22 14:12 1248XDebug Support In PDT 1.0 :htt ... -
file_get_contents的超时处理
2010-08-17 14:57 2144转自:http://www.neatstudio.com/sh ... -
在php 5.2版本之前使用的json_encode和json_decode函数
2010-08-13 09:33 1831http://mike.teczno.com/JSON/JSO ... -
月份处理函数
2010-08-11 22:00 1013function period_diff($in_dateLo ... -
配置xdebug
2010-08-10 09:19 970zend_extension = "D:/xampp ... -
判断在linux以命令行执行的文件是否还在执行
2010-06-03 10:37 2135// 取得当前程序进程,用来判断是否可以执行 $gather ... -
PHP分页
2010-05-05 07:15 1127<?php header("content- ... -
JavaBridge
2010-02-10 16:11 864中文翻译及使用手册 http://programfan.co ... -
PHP 压缩网站上的文件,并返回下载
2009-08-27 20:51 2708<?php $zipFileName = " ... -
递归删除目录及目录中的文件
2009-08-27 20:24 1229<?php /** * 递归删除目录及目录中的文件 ... -
PHP验证码程序:session生成图片
2009-08-07 15:39 3880昨天捣鼓了一下PHP验证码并生成图片程序,采用了sessi ... -
Apache的rewrite规则详细介绍
2009-06-01 22:52 1355rewrite标志 R [=code](for ... -
php mail 支持UTF-8,附件
2009-03-06 14:19 2888<?php class mime_mail { var ... -
php 多语言切换
2009-02-27 09:55 10170目录结构: //================= ... -
包含其他目录的文件
2009-02-02 16:57 988<?php include_once dirname(_ ... -
时区表 Territory Containment
2008-11-11 11:44 1121时区表 http://unicode.org/cldr/dat ...
相关推荐
SAP 方法论 Run SAP Methodology How to Implement End-to-End Solution Operations
This application shows you how to implement professional looking scrolling credits. There are two different demos: top to bottom and left to right. You can click on the credited individual to send him...
Machine Learning: Step-by-Step Guide To Implement Machine Learning Algorithms with Python By 作者: Rudolph Russell ISBN-10 书号: 1719528403 ISBN-13 书号: 9781719528405 出版日期: 2018-05-22 pages ...
### 如何在表维护中实现事件 本文将详细介绍如何在表维护中实现事件,并通过一个具体案例来展示这一过程。该方法特别适用于在创建新条目时进行多种验证和检查。 #### 场景设定 假设我们需要更新一张自定义表...
在MATLAB中实现面向对象编程(Object-Oriented Programming,OOP)原理是提升代码组织性和可维护性的重要方法。MATLAB虽然最初设计为一种数值计算工具,但随着时间的发展,它逐渐增加了对OOP的支持。...
【标题】: "Visual Basic项目中的分割条实现示例应用" 【描述】: 在软件开发中,分割条(Splitter Bar)是一种常见的用户界面元素,它允许用户动态调整两个或多个区域的大小,以优化视图空间。...
### 如何实施SCP-ECG(第二部分) #### 引言 随着信息技术的进步与医疗行业的融合不断加深,电生理信号的记录与传输变得尤为重要。在众多应用中,心电图(ECG)作为早期检测心脏疾病的一项非侵入性检查手段,在西方...
This book will teach you how to deploy large-scale datasets in deep neural networks with Hadoop for optimal performance. Starting with understanding what deep learning is, and what the various models ...
to implement a variety of interesting techniques and special effects, such as working with animated character meshes, picking, environment mapping, normal mapping, real-time shadows, and ambient ...
在编程领域,为应用程序添加打印支持是一项常见的任务,它允许用户将程序中的数据或界面输出到物理媒介,如纸张或者电子PDF文档。本篇将详细介绍如何在你的程序中实现打印支持,涉及到的关键知识点包括控件操作、...
在构建世界级的信息安全和数据安全体系时,身份与访问管理(IAM)扮演着至关重要的角色。IAM项目的目标是实现高效且低成本的业务流程,有效管理企业安全风险,并确保符合IAM的法规要求。以下是对IAM转型项目的详细...
The book also contains a number of R labs with detailed explanations on how to implement the various methods in real life settings, and should be a valuable resource for a practicing data scientist.
Part II shows how to implement elementary 3D techniques, such as defining 3D geometry, lighting, texturing, alpha blending, and stenciling, using shaders and the HLSL. Part III is largely about ...
Part II shows how to implement fundamental tasks in Direct3D, such as initialization, defining 3D geometry, setting up cameras, creating vertex, pixel, and geometry shaders, lighting, texturing, ...
You'll learn about unit testing and how to implement it in CakePHP. This approach to coding leads to better code, better applications, and better programming habits. With this knowledge your PHP ...
This book will help you understand how to implement microservice-based systems from scratch. You’ll start off by understanding the core concepts and framework, before focusing on the high-level ...
Teradata Cookbook Over 85 recipes to implement efficient data warehousing solutions 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 查看此书详细信息请在美国亚马逊官网搜索此书
通过以上知识点的梳理,我们可以看出,《Planing to Implement Service Management》这本书提供了一个全面而深入的指南,帮助读者理解和实施服务管理的原则和实践。无论是对于刚接触该领域的初学者还是寻求进一步...