基于服务器端推送事件的comet技术

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

//nodejs 实现的服务器端代码
var http = require('http');//nodejs http 服务器
//聊天客户端使用的html文件 在下面会用

var clientui =require('fs').readFileSync('comet.html');

var emulation = require('fs').readFileSync('comet.js');

//ServerResponse 对象数组,用于接收发送的事件
var clients = [];
//每20秒发送一条注释到客户端
//这样他们就不会关闭连接再重连
setInterval(function(){
  clients.forEach(function(client){
     client.write(':ping?n');
  });
},20000);

//创建一个新的服务器
var server = new http.Server();

server.on('request',function(request,response){
    //解析请求的url
    var url = require('url').parse(request.url);
    //如果请求是发送到'/',服务器就发送客户端聊天室UI
    if(url.pathname === '/'){//如果请求是发送到 /服务器就发送客户端聊天室UI
       response.writeHead(200,{'Content-Type':'text/html'});
       response.write('<script>'+emulation+'</script>');
       response.write(clientui);
       response.end();
       return;
    }else if(url.pathname !=='/chat'){//如果发送的/chat这之外的地址那么就返回404
         response.writeHead(404);
         response.end();
         return;
    }
    //如果请求类型是post 那么就有一个客户端发送了一条新消息
    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();
            //将消息转换成文本/事件流格式 
            //确保每一行的浅醉都是“data:”
            //并以两个换行符结束
            message = 'data: '+body.replace('\n','\ndata: ')+'\r\n\r\n';
            //发送消息给所有监听的客户端
            clients.forEach(function(client){
                client.write(message);
            });
        });
    }else{
        //如果不是POST请求则客户端正在请求一组消息
        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();
    //通过EventSource注册最新消息的通知
    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();
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值