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 ...
随机推荐
- 字符编码 and cpp
预备知识 字符:抽象的最小文本单位.仅代表符合没有实际意义(如:¥, a, 国) 字符集:字符的集合(如gb2312, ASCII, UNICODE) 编码:是对字符集的描述,计算机要准确的处理各种字 ...
- 开源.net 混淆器ConfuserEx介绍
今天给大家介绍一个开源.net混淆器——ConfuserEx http://yck1509.github.io/ConfuserEx/ 由于项目中要用到.net 混淆器,网上搜寻了很多款,比如Dotf ...
- 管理Cookie的插件——jquery.cookie.js
下载地址:http://plugins.jquery.com/cookie/ jquery.cookie中的操作: 一.创建cookie: 1.创建一个会话cookie: $.cookie('cook ...
- MVC5+EF6 入门完整教程11--细说MVC中仓储模式的应用
摘要: 第一阶段1~10篇已经覆盖了MVC开发必要的基本知识. 第二阶段11-20篇将会侧重于专题的讲解,一篇文章解决一个实际问题. 根据园友的反馈, 本篇文章将会先对呼声最高的仓储模式进行讲解. 文 ...
- 【转】 MySQL与PostgreSQL:该选择哪个开源数据库?哪一个更好?
转载地址:http://www.infoq.com/cn/news/2013/12/mysql-vs-postgresql 如果打算为项目选择一款免费.开源的数据库,那么你可能会在MySQL与Post ...
- Java 新手学习 CSS样式列表 排版 格式布局
1,样式表分为 内联样式表 内嵌样式表 外部样式表 三种. 内联样式表是直接写在标签里面的 比如 <p style=“”></p> <div style=& ...
- ssh 免密码登录
1.在本机下生成公钥/私钥对. ssh-keygen -t rsa -P '' -P表示密码,-P '' 就表示空密码,也可以不用-P参数,这样就要三车回车,用-P就一次回车.它在/home/yaoy ...
- 2016年江西理工大学C语言程序设计竞赛(初级组)
问题 A: 木棒根数 解法:把所有的情况保存下来,加一下就好 #include<bits/stdc++.h> using namespace std; map<char,int> ...
- [问题2015S10] 复旦高等代数 II(14级)每周一题(第十一教学周)
[问题2015S10] 设 \(A\) 为 \(n\) 阶实方阵, 证明: 存在 \(n\) 阶非异实对称阵 \(R\), 使得 \(A'=R^{-1}AR\), 即 \(A\) 可通过非异实对称阵 ...
- StudyFoxCMS-6
1.phpstrom中安装emmet File=>Settings=>Plugins=>右侧搜索框搜索“emmet”=>点击下方中间按钮“Browse repositories ...