function process(data){
console.log(data);
}
var dataStream = function (url) {
var ifr = document.createElement("iframe"),timer;
ifr.src = url;
document.body.appendChild(ifr);
};
dataStream('http://localhost:8088/htmlfile');
客户端为了简单起见,定义对数据处理就是打印出来。
服务端代码:
var http=require('http');
var fs = require("fs");
var count=0;
var server=http.createServer(function(req,res){
if(req.url=='/htmlfile'){
res.setHeader('content-type', 'text/html');
var timer=setInterval(function(){
sendRandomData(timer,res);
},2000);
};
if(req.url=='/'){
fs.readFile("./htmlfile-stream.html", "binary", function(err, file) {
if (!err) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(file, "binary");
res.end();
}
});
}
}).listen(8088,'localhost');
function sendRandomData(timer,res){
var randomNum=Math.floor(10000*Math.random());
console.log(randomNum.toString());
if(count++==10){
clearInterval(timer);
res.end("<script type=\"text/javascript\">parent.process('"+randomNum.toString()+"')</script>");
}
res.write("<script type=\"text/javascript\">parent.process('"+randomNum.toString()+"')</script>");
}
function callback(data){
console.log("获得的跨域数据为:"+data);
}
function sendJsonp(url){
var oScript=document.createElement("script");
oScript.src=url;
oScript.setAttribute('type',"text/javascript");
document.getElementsByTagName('head')[0].appendChild(oScript);
}
setInterval(function(){
sendJsonp('http://localhost:8088/jsonp?cb=callback');
},1000);
服务端代码:
var http=require('http');
var url=require('url');
var server=http.createServer(function(req,res){
if(/\/jsonp/.test(req.url)){
var urlData=url.parse(req.url,true);
var methodName=urlData.query.cb;
res.writeHead(200,{'Content-Type':'application/javascript'});
//res.end("<script type=\"text/javascript\">"+methodName+"("+new Date().getTime()+");</script>");
res.end(methodName+"("+new Date().getTime()+");");
//res.end(new Date().toString());
}
}).listen(8088,'localhost');
server.on('connection',function(socket){
console.log("客户端连接已经建立");
});
server.on('close',function(){
console.log('服务器被关闭');
});
window.onload=function(){
var ws=new WebSocket("ws://127.0.0.1:8088");
var oText=document.getElementById('message');
var oSend=document.getElementById('send');
var oClose=document.getElementById('close');
var oUl=document.getElementsByTagName('ul')[0];
ws.onopen=function(){
oSend.onclick=function(){
if(!/^\s*$/.test(oText.value)){
ws.send(oText.value);
}
};
};
ws.onmessage=function(msg){
var str="<li>"+msg.data+"</li>";
oUl.innerHTML+=str;
};
ws.onclose=function(e){
console.log("已断开与服务器的连接");
ws.close();
}
}