我的第一个comet长连接例子
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<title>大家来玩Comet</title>
<script src="../statics/js/jquery-1.9.1.min.js"></script>
<script src="../statics/js/plugins/placeholder.js"></script><!--让IE10以下也支持placeholder-->
<style type="text/css">
#word{width:450px;height:40px;padding:0 10px;border:#ddd 2px solid; line-height:40px\9}
#btn{height:44px; vertical-align:middle;position:relative;top:-2px;+vertical-align:bottom;+top:-1px;}
#content{width:644px;height:300px;+width:720px;margin:0 auto;background:#f7f7f7;padding:10px; overflow:hidden;overflow-y:auto}
.talkCloud{text-align:left;line-height:40px;} </style>
</head>
<body>
<script type="text/javascript">
$(function(){ /*cookie 操作*/
var cookieUtil = {
//获取cookie
get:function(name){
var cookieName = encodeURIComponent(name)+"=",
cookieStart = document.cookie.indexOf(cookieName),
cookieValue = null; if(cookieStart>-1){
var cookieEnd = document.cookie.indexOf(";",cookieStart);
if(cookieEnd==-1){
cookieEnd = document.cookie.length;
}
cookieValue = decodeURIComponent(document.cookie.substring(cookieStart+cookieName.length,cookieEnd));
}
return cookieValue;
}, //设置cookie
set:function(name,value,expires,path,domain,secure){
var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);
if(expires instanceof Date){
cookieText += "; expires="+expires.toGMTString();
}
if(path){
cookieText += "; path=" + path;
}
if(domain){
cookieText += "; domain" + domain;
}
if(secure){
cookieText += "; secure";
}
document.cookie = cookieText;
return value;
}, //删除cookie
unset:function(name,path,domain,secure){
this.set(name,"",new Date(0),path,domain,secure);
}
};
window.cookieUtil = cookieUtil; //comet长连接例子
var clickTimes = 0;//点击计数
var timestamp = 0;//文件时间戳
var url = 'server.php';//后端服务器脚本地址
var noerror = true;
var ajax; function handleResponse(response){
$('#content').append('<div class="talkCloud">' + response['msg'] + '</div>');
$("#content").scrollTop($("#content")[0].scrollHeight);
}
function connect() {
ajax = $.ajax(url, {
type: 'get',
data: { 'timestamp' : timestamp,'uname' : cookieUtil.get("uname")},
success: function(transport) {
eval('var response = '+transport);
timestamp = response['timestamp'];
handleResponse(response);
noerror = true;//判断ajax发送成功的回调函数是否执行成功的标志;
},
complete: function(transport) {
(!noerror) && setTimeout(function(){ connect() }, 5000) || connect();
noerror = false;//执行完一次完成回调函数是否执行成功的标志
}
});
} function doRequest(request) {
$.ajax(url, {
type: 'get',
data: { 'msg' : request,'uname':cookieUtil.get("uname") }
});
}; $('#cometForm').on("submit",function(){
clickTimes++;
if(clickTimes == 1){
cookieUtil.set("uname",$('#word').val(),'','','','');
};
doRequest($('#word').val());
$('#word').val('');
return false;
}); connect(); });
</script>
<center>
<h2>大家来玩长连接</h2>
<div id="content"></div>
<div style="margin: 5px 0;">
<form action="javascript:void(0);" id="cometForm" method="get">
<input id="word" name="word" type="text" value="" placeholder="第一次请输入你自己的姓名">
<input name="submit" type="submit" id="btn" value="我就是个摆设,其实敲回车也可以提交"> </form></div>
</center>
</body>
</html>
<?php $filename = 'F:\phpStudy\WWW\boss\cometDemo\data.txt'; // 消息都储存在这个文件中
$msg = isset($_GET['msg']) ? $_GET['msg'] : '';
$uname = isset($_GET['uname']) ? $_GET['uname']:''; if ($msg != ''){ //fopen()方法:如果文件不存在,则创建,如果存在则打开文件。它的第二个参数是打开的文件的模式,w表示覆盖式只写,详见《PHP高程设计》183页
// $fn = fopen($filename,'w');
// fwrite($fn,$uname.": ".$msg);
// fclose($fn);
file_put_contents($filename,$uname.": ".$msg); //此方法已不建议使用 // file_put_contents($filename,"您的名字是: ".$msg); } // 不停的循环,直到储存消息的文件被修改
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif){ // 如果数据文件已经被修改
usleep(100000); // 100ms暂停 缓解CPU压力
clearstatcache(); //清除缓存信息
$currentmodif = filemtime($filename);
} // 返回json数组
$response = array();
$response['msg'] = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
flush(); ?>
placeholder.js 这个东西也不错,贴在这里,省的去找了:
(function($) {
/**
* http://blog.csdn.net/mycwq/
* 2012/11/28 15:12
*/ var placeholderfriend = {
focus: function(s) {
s = $(s).hide().prev().show().focus();
var idValue = s.attr("id");
if (idValue) {
s.attr("id", idValue.replace("placeholderfriend", ""));
}
var clsValue = s.attr("class");
if (clsValue) {
s.attr("class", clsValue.replace("placeholderfriend", ""));
}
}
} //判断是否支持placeholder
function isPlaceholer() {
var input = document.createElement('input');
return "placeholder" in input;
}
//不支持的代码
if (!isPlaceholer()) {
$(function() { var form = $(this); //遍历所有文本框,添加placeholder模拟事件
var elements = form.find("input[type='text'][placeholder]");
elements.each(function() {
var s = $(this);
var pValue = s.attr("placeholder");
var sValue = s.val();
if (pValue) {
if (sValue == '') {
s.val(pValue);
}
}
}); elements.focus(function() {
var s = $(this);
var pValue = s.attr("placeholder");
var sValue = s.val();
if (sValue && pValue) {
if (sValue == pValue) {
s.val('');
}
}
}); elements.blur(function() {
var s = $(this);
var pValue = s.attr("placeholder");
var sValue = s.val();
if (!sValue) {
s.val(pValue);
}
}); //遍历所有密码框,添加placeholder模拟事件
var elementsPass = form.find("input[type='password'][placeholder]");
elementsPass.each(function(i) {
var s = $(this);
var pValue = s.attr("placeholder");
var sValue = s.val();
if (pValue) {
if (sValue == '') {
//DOM不支持type的修改,需要复制密码框属性,生成新的DOM
var html = this.outerHTML || "";
html = html.replace(/\s*type=(['"])?password\1/gi, " type=text placeholderfriend")
.replace(/\s*(?:value|on[a-z]+|name)(=(['"])?\S*\1)?/gi, " ")
.replace(/\s*placeholderfriend/, " placeholderfriend value='" + pValue
+ "' " + "onfocus='placeholderfriendfocus(this);' ");
var idValue = s.attr("id");
if (idValue) {
s.attr("id", idValue + "placeholderfriend");
}
var clsValue = s.attr("class");
if (clsValue) {
s.attr("class", clsValue + "placeholderfriend");
}
s.hide();
s.after(html);
}
}
}); elementsPass.blur(function() {
var s = $(this);
var sValue = s.val();
if (sValue == '') {
var idValue = s.attr("id");
if (idValue) {
s.attr("id", idValue + "placeholderfriend");
}
var clsValue = s.attr("class");
if (clsValue) {
s.attr("class", clsValue + "placeholderfriend");
}
s.hide().next().show();
}
}); });
}
window.placeholderfriendfocus = placeholderfriend.focus;
})(jQuery);
HTML5 shiv也贴上来:
/*
HTML5 Shiv v3.6.2 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed.g
*/
(function(l,f){function m(){var a=e.elements;return"string"==typeof a?a.split(" "):a}function i(a){var b=n[a[o]];b||(b={},h++,a[o]=h,n[h]=b);return b}function p(a,b,c){b||(b=f);if(g)return b.createElement(a);c||(c=i(b));b=c.cache[a]?c.cache[a].cloneNode():r.test(a)?(c.cache[a]=c.createElem(a)).cloneNode():c.createElem(a);return b.canHaveChildren&&!s.test(a)?c.frag.appendChild(b):b}function t(a,b){if(!b.cache)b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag();
a.createElement=function(c){return!e.shivMethods?b.createElem(c):p(c,a,b)};a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+m().join().replace(/\w+/g,function(a){b.createElem(a);b.frag.createElement(a);return'c("'+a+'")'})+");return n}")(e,b.frag)}function q(a){a||(a=f);var b=i(a);if(e.shivCSS&&!j&&!b.hasCSS){var c,d=a;c=d.createElement("p");d=d.getElementsByTagName("head")[0]||d.documentElement;c.innerHTML="x<style>article,aside,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}</style>";
c=d.insertBefore(c.lastChild,d.firstChild);b.hasCSS=!!c}g||t(a,b);return a}var k=l.html5||{},s=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,r=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,j,o="_html5shiv",h=0,n={},g;(function(){try{var a=f.createElement("a");a.innerHTML="<xyz></xyz>";j="hidden"in a;var b;if(!(b=1==a.childNodes.length)){f.createElement("a");var c=f.createDocumentFragment();b="undefined"==typeof c.cloneNode||
"undefined"==typeof c.createDocumentFragment||"undefined"==typeof c.createElement}g=b}catch(d){g=j=!0}})();var e={elements:k.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup main mark meter nav output progress section summary time video",version:"3.6.2",shivCSS:!1!==k.shivCSS,supportsUnknownElements:g,shivMethods:!1!==k.shivMethods,type:"default",shivDocument:q,createElement:p,createDocumentFragment:function(a,b){a||(a=f);if(g)return a.createDocumentFragment();
for(var b=b||i(a),c=b.frag.cloneNode(),d=0,e=m(),h=e.length;d<h;d++)c.createElement(e[d]);return c}};l.html5=e;q(f)})(this,document);
window._browserIsNotSupported = true;
if(window.attachEvent){
window.attachEvent('onload', function(){
var lowestSupportedIEVersion = 8;
if(window.LOWEST_IE_VERSION != undefined){
lowestSupportedIEVersion = window.LOWEST_IE_VERSION;
}
var el = document.createElement('div'),
elStyle = el.style,
docBody = document.getElementsByTagName('body')[0],
linkStyle = 'color:#06F;text-decoration: underline;';
el.innerHTML = '尊敬的小伙伴们:<br />'+
'使用慧业网Boss/CRM系统控制台需要安装Internet Explorer 8或更新版本的浏览器,'+
'请<a href="http://windows.microsoft.com/zh-cn/internet-explorer/download-ie" style="'+linkStyle+'" target="_blank">下载安装IE' + lowestSupportedIEVersion + '</a>(或更新)。'+
'也可以在其他浏览器,'+
'如<a href="http://rj.baidu.com/soft/detail/14744.html" style="'+linkStyle+'" target="_blank">Chrome</a>'+
'或<a href="http://www.firefox.com.cn/download/" style="'+linkStyle+'" target="_blank">Firefox</a>火狐中打开本系统。';
// elStyle.width = '100%';
elStyle.width = '720px';
elStyle.color = '#000';
elStyle.fontSize = '14px';
elStyle.lineHeight = '200%';
elStyle.margin = '60px auto';
elStyle.backgroundColor = '#fffbd5';
elStyle.border = '1px solid #CCC';
elStyle.padding = '24px 48px';
// elStyle.background = '#F00 url(styles/images/not-support-ie67.png) 48px 48px no-repeat';
// elStyle.padding = '40px 40px 48px 160px';
docBody.innerHTML = '';
docBody.appendChild(el);
// docBody.insertBefore(el,docBody.firstChild);
});
}
我的第一个comet长连接例子的更多相关文章
- 转:基于ASP.NET的Comet长连接技术解析
原文来自于: Comet技术原理 来自维基百科:Comet是一种用于web的技术,能使服务器能实时地将更新的信息传送到客户端,而无须客户端发出请求,目前有两种实现方式,长轮询和iframe流. 简单的 ...
- 分享一个基于长连接+长轮询+原生的JS及AJAX实现的多人在线即时交流聊天室
实现网页版的在线聊天室的方法有很多,在没有来到HTML5之前,常见的有:定时轮询.长连接+长轮询.基于第三方插件(如FLASH的Socket),而如果是HTML5,则比较简单,可以直接使用WebSoc ...
- Comet:基于 HTTP 长连接的“服务器推”技术
“服务器推”技术的应用 请访问 Ajax 技术资源中心,这是有关 Ajax 编程模型信息的一站式中心,包括很多文档.教程.论坛.blog.wiki 和新闻.任何 Ajax 的新信息都能在这里找到. c ...
- Comet技术详解:基于HTTP长连接的Web端实时通信技术
前言 一般来说,Web端即时通讯技术因受限于浏览器的设计限制,一直以来实现起来并不容易,主流的Web端即时通讯方案大致有4种:传统Ajax短轮询.Comet技术.WebSocket技术.SSE(Ser ...
- 转载:Comet:基于 HTTP 长连接的“服务器推”技术
转自:http://www.ibm.com/developerworks/cn/web/wa-lo-comet/ 很多应用譬如监控.即时通信.即时报价系统都需要将后台发生的变化实时传送到客户端而无须客 ...
- [转载] Comet:基于 HTTP 长连接的“服务器推”技术
转载自http://www.ibm.com/developerworks/cn/web/wa-lo-comet/ “服务器推”技术的应用 传统模式的 Web 系统以客户端发出请求.服务器端响应的方式工 ...
- Comet:基于 HTTP 长连接的“服务器推”技术(转载)
“服务器推”技术的应用 传统模式的 Web 系统以客户端发出请求.服务器端响应的方式工作.这种方式并不能满足很多现实应用的需求,譬如: 监控系统:后台硬件热插拔.LED.温度.电压发生变化: 即时通信 ...
- 【转】Comet:基于 HTTP 长连接的“服务器推”技术
原文链接:http://www.ibm.com/developerworks/cn/web/wa-lo-comet/ 很多应用譬如监控.即时通信.即时报价系统都需要将后台发生的变化实时传送到客户端而无 ...
- 网络编程懒人入门(八):手把手教你写基于TCP的Socket长连接
本文原作者:“水晶虾饺”,原文由“玉刚说”写作平台提供写作赞助,原文版权归“玉刚说”微信公众号所有,即时通讯网收录时有改动. 1.引言 好多小白初次接触即时通讯(比如:IM或者消息推送应用)时,总是不 ...
随机推荐
- 关于页面刷新或者调用方法事获取不到元素信息或者出现缺少对象错误的换位思考setTimeout的使用
这两天客户的需求不能定下来,做闲人好长时间了,不如来整理下最近碰到的一些个小麻烦. 正题: 场景一. 最近在开发的过程中使用到了百度的富客户端文本编辑器(ueditor)---这是一款功能很强大的文本 ...
- jQuery代码片段
禁用页面右键菜单 $(document).bind('contextmenu', function(){ return false; }); 浏览器判断 $.browser.version $.bro ...
- 机器学习之K近邻算法(KNN)
机器学习之K近邻算法(KNN) 标签: python 算法 KNN 机械学习 苛求真理的欲望让我想要了解算法的本质,于是我开始了机械学习的算法之旅 from numpy import * import ...
- MVC中ActionFilterAttribute用法并实现统一授权
MVC中ActionFilterAttribute经常用来处理权限或者统一操作时的问题. 先写一个简单的例子,如下: 比如现在有一个用户管理中心,而这个用户管理中心需要登录授权后才能进去操作或浏览信息 ...
- linux常用命令(6)mv命令
mv命令是move的缩写,可以用来移动文件或者将文件改名(move (rename) files),是Linux系统下常用的命令,经常用来备份文件或者目录.1 命令格式:mv [选项] 原文件或目录 ...
- IOS开发笔记(4)数据离线缓存与读取
IOS开发笔记(4)数据离线缓存与读取 分类: IOS学习2012-12-06 16:30 7082人阅读 评论(0) 收藏 举报 iosiOSIOS 方法一:一般将服务器第一次返回的数据保存在沙盒里 ...
- C语言-cout<<"123"<<"45"<<endl;
VC中头文件为:#include <iostream.h> 这个在c中没有.是C++引进的. cout<头文件#include中printf()类似. 只是不需要标明数据类型. en ...
- Keil C51处理可重入函数问题的探讨
在程序设计中,变量具体可以分为四种类型:全局变量.静态全局变量.局部变量.静态局部变量.这几种变量类型对函数的可重入产生的重大的影响,因为不同的编译器采用不同的策略. 针对51的存储区有限,keil ...
- (转)linux下fork的运行机制
转载http://www.cnblogs.com/leoo2sk/archive/2009/12/11/talk-about-fork-in-linux.html 给出如下C程序,在linux下使用g ...
- <转载>构造函数与拷贝构造函数
原文地址http://www.cnblogs.com/waynelu/archive/2012/07/01/2572264.html 构造函数 构造函数.析构函数与赋值函数是每个类最基本的函数. 对于 ...