html代码部分 comet.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>基于服务器端推送事件的comet技术</title>
<style type="text/css" media="screen">
*{
margin:0;
padding:0;
}
body{
background:#000;
}
input.input-in{
width:500px;
height:35px;
line-height:35px;
text-align:left;
color:#000;
background:#fff;
border:1px solid #333;
text-indent:10px;
}
input:focus{
background:purple;
color:#fff;
box-shadow:0px 0px 15px rgba(255,0,0,0.5);
}
.chat-message{
width:500px;
height:400px;
background:#fff;
color:#999;
margin:0 auto;
overflow-y: scroll;
}
.chat-message li{
width:100%;
height:25px;
line-height:25px;
text-align:left;
text-indent:15px;
margin-bottom:10px;
background:blue;
color:#fff;
list-style-type:none;
}
.chat-message li:nth-child(2n+1){
background:purple;
}
.chat-input{
text-align:center;
width:500px;
height:35px;
margin:0 auto;
}
</style>
</head>
<body>
<ul class="chat-message">
</ul>
<div class="chat-input">
<input type="text" class="input-in"/>
</div>
</body>
</html>
服务器端server.js
var http = require('http');
var clientui =require('fs').readFileSync('comet.html');
var emulation = require('fs').readFileSync('comet.js');
var clients = [];
setInterval(function(){
clients.forEach(function(client){
client.write(':ping?n');
});
},20000);
var server = new http.Server();
server.on('request',function(request,response){
var url = require('url').parse(request.url);
if(url.pathname === '/'){
response.writeHead(200,{'Content-Type':'text/html'});
response.write('<script>'+emulation+'</script>');
response.write(clientui);
response.end();
return;
}else if(url.pathname !=='/chat'){
response.writeHead(404);
response.end();
return;
}
if(request.method === 'POST'){
console.log('POST');
request.setEncoding('utf8');
var body ='';
request.on('data',function(chunk){body += chunk;});
request.on('end',function(){
response.writeHead(200);
response.end();
message = 'data: '+body.replace('\n','\ndata: ')+'\r\n\r\n';
clients.forEach(function(client){
client.write(message);
});
});
}else{
response.writeHead(200,{'Content-Type':'text/event-stream'});
response.write('data: Connected\n\n');
response.connection.on('end',function(){
clients.splice(clients.indexOf(response),1);
response.end();
});
clients.push(response);
}
});
server.listen(5000);
客户端 comet.js
function init(){
var nickname = prompt('请输入您的名字!');
var input = document.getElementsByClassName('input-in')[0];
var chat = document.getElementsByClassName('chat-message')[0];
console.log(chat);
input.focus();
var chat = new EventSource('/chat');
chat.onmessage = function(event){
var msg = event.data;
chat.innerHTML += '<li>'+msg+'</li>';
}
input.onchange=function(event){
var msg = nickname +' : ' +input.value;
var xhr = new XMLHttpRequest();
xhr.open('POST','/chat');
xhr.setRequestHeader('Content-Type','text/plain;charset=UTF-8');
xhr.send(msg);
input.value = '';
}
}
window.onload = function(){
init();
};