EventSource
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>EventSource</title>
</head>
<body>
<script>
window.onload=function(){
name();
function name(){
var username=prompt("请输入您的昵称");
if(!username){
return false;
}
var xml=new XMLHttpRequest();
xml.open("POST","/addUser");
xml.send("name="+username);
xml.onreadystatechange=function(){
if(xml.status=200&&xml.readyState==4){
var res=JSON.parse(xml.responseText)
if(res.success=="ok"){
alert("欢迎你的加入");
window.hiddenValue.value=res.name;
var es = new EventSource("/chat");
es.addEventListener("message", function(e){
var temp=document.createElement("li");
temp.innerHTML= e.data;
window.message.scrollIntoView();
window.content.appendChild(temp);
},false);
}else{
alert(res.msg+",如果你还想加入,行刷新重新输入用户名称");
//本来用的递归,但是体验不好,就改了
//name();
}
}
}
}
var div=document.getElementsByTagName("div")[0]
div.style.width=window.innerWidth+"px";
}
function sendMessage(){
var message=window.message.value;
if(message.trim()){
var b=new XMLHttpRequest();
b.open("POST","/chat");
b.send("message="+window.message.value+"&name="+ window.hiddenValue.value);
}
} </script>
<div>
<ul id="content">
</ul>
</div>
<input type="text" name="message" id="message" /><input type="button" value="发送" onclick="sendMessage()"/>
<input type="hidden" id="hiddenValue">
</body>
</html>
var server=require("http");
var url=require("url");
var file=require("fs");
var querystring=require("querystring");
var clientName=[];
var responseArray=[]; server.createServer(function (request, response) {
var message="";
var name="";
var urlContent=url.parse(request.url); //首页
if(urlContent.pathname=="/"){
response.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
file.readFile("../views/Index.html",function(err,data){
response.end(data);
})
return false;
}
else if(urlContent.pathname=="/chat"){ //发送消息
if(request.method=="POST"){ //并不能根据response得到正确的name索引,所以前台传递name
request.on("data",function(data){
data= querystring.parse(data.toString());
message+=decodeURIComponent(data.message.trim());
name+=decodeURIComponent(data.name.trim());
})
request.on("end",function(){
responseArray.forEach(function(i){
i.write("data:"+name+"说:"+message+"\n\n");
})
})
response.end();
}else{ //建立长连接,保存相应
responseArray.push(response);
response.writeHead(200,{"Content-Type":"text/event-stream"});
response.write("data:已连接至服务器\n\n");
request.connection.on("end",function(){
var index=responseArray.indexOf(response)
clientName.splice(index,1);
responseArray.splice(index,1);
response.end();
})
}
}else if(urlContent.pathname=="/addUser"){ //添加用户名
request.on("data",function(data){
data= querystring.parse(data.toString().trim());
name+=decodeURIComponent(data.name.trim());
});
request.on("end",function(){
response.writeHead(200,{"Content-Type":"text/json;charset=utf-8"});
if(clientName.some(function(i){
if(i==name) return true;
})){
response.write("{\"success\":\"fail\",\"msg\":\"用户名重复\"}")
}else{
response.write("{\"success\":\"ok\",\"name\":\""+name+"\"}");
responseArray.forEach(function(i){
i.write("data:欢迎"+name+"的加入"+"\n\n");
})
clientName.push(name);
}
response.end(); })
}
else{
response.writeHead(404,{"Content-Type":"text/json"});
response.end();
}
}).listen(8012);
后台使用Node.js 博主是一个新人,会有很多不太适合的代码,希望大家能多多帮助。代码中注意路径问题。代码仍有缺陷,现在连接断开,不一定能够删除用户名称。以下的总结都是基于上面的代码的,如果有其他情况,麻烦您给我说一下,谢谢。
EventSource的更多相关文章
- Html5实践之EventSource
最近尝试了一下服务器端的推送,之前的做法都是客户端轮询,定时向服务器发送请求.但这造成了我的一些困扰: 1:轮询是由客户端发起的,那么在服务端就不能判别我要推送的内容是否已经过期,因为我很难判断某个信 ...
- EventSource (node.js 与 OC)
node.js服务器代码: var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, ...
- HTML5 EventSource的用法
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- 服务端事件EventSource揭秘
服务端推 服务端推,指的是由服务器主动的向客户端发送消息(响应).在应用层的HTTP协议实现中,"请求-响应"是一个round trip,它的起点来自客户端,因此在应用层之上无法实 ...
- H5 EventSource 实现web页面推送功能demo
/** * H5 EventSource 实现web页面推送功能demo */ var serverData,statusDiv; var SERVER_URL = "index.php&q ...
- polyfill-eventsource added missing EventSource to window ie浏览器 解决方案
今天遇到一个 ie浏览器显示空白,报错内容是: polyfill-eventsource added missing EventSource to window的问题, import 'babel-p ...
- EventSource 对象用于接收服务器发送事件通知,是网页自动获取来自服务器的更新
//--------------------------------客户端代码----------------------------- if(typeof(EventSource) !== &quo ...
- 通过html5 的EventSource来进行数据推送
以往我们要获取服务器的数据更新,一般通过ajax的定时请求,不过这样效率就低了.我们通过html5的EventSource可以很方便的获取服务器的数据更新,不过IE好像不支持. 例1如下: ind ...
- 【JavaScript】论一个低配版Web实时通信库是如何实现的之二( EventSource篇)
前情提要 「 话说上回说到!那WebSocket大侠,巧借http之内力,破了敌阵的双工鸳鸯锁,终于突出重围. 然而玄难未了,此时web森林中飞出一只银头红缨枪,划破夜色. "莫非!?&qu ...
随机推荐
- 夺命雷公狗-----React---10--组建嵌套进行数据遍历
先写一个组建... 然后进行嵌套.. <!DOCTYPE html> <html lang="en"> <head> <meta char ...
- 夺命雷公狗-----React---2--组建
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 《zw版·Halcon-delphi系列原创教程》 Halcon分类函数001·3D函数
<zw版·Halcon-delphi系列原创教程> Halcon分类函数001·3D函数 为方便阅读,在不影响说明的前提下,笔者对函数进行了简化: :: 用符号“**”,替换:“proce ...
- Using MSBuild to publish a VS 2012 SSDT .sqlproj database project
http://blog.danskingdom.com/using-msbuild-to-publish-a-vs-2012-ssdt-sqlproj-database-project-the-sam ...
- Android MimeType的用法和几种类型
关于MIME TYPE描述 多用途互联网邮件扩展(MIME,Multipurpose Internet Mail Extensions)是一个互联网标准,它扩展了电子邮件标准,使其能够支持非ASCII ...
- 将HTML5 Canvas的内容保存为图片借助toDataURL实现
将HTML5 Canvas的内容保存为图片主要思想是借助Canvas自己的API - toDataURL()来实现,具体实现如下,感兴趣的朋友可以参考下哈,希望对你有所帮助 <html> ...
- Android 网络请求库volley的封装,让请求更方便
首先封装一下volley 请求 public class CustomRequest extends StringRequest { private static final String TAG = ...
- Linux之一条命令解决常见问题(持续更新)
# 1.删除0字节文件 find -type f -size 0 -exec rm -f {} \; # 2.批量文件重命名 find . -type f -name "*.txt" ...
- CentOS 更改yum源与更新系统
FROM:http://www.cnblogs.com/lightnear/archive/2012/10/03/2710952.html [1] 首先备份/etc/yum.repos.d/CentO ...
- [课程设计]Scrum 1.5 多鱼点餐系统开发进度(点餐页面框架修复及继续布置)
Scrum 1.5 多鱼点餐系统开发进度(点餐页面框架修复及继续布置) 1.团队名称:重案组 2.团队目标:长期经营,积累客户充分准备,伺机而行 3.团队口号:矢志不渝,追求完美 4.团队选题:餐厅 ...