1. 程式人生 > >nodejs即時聊天

nodejs即時聊天

roo itl hat 用戶名 split 代碼 send ext seconds

一直想做一個即時聊天的應用,前幾天看到了socket.io,感覺還不錯。自己略加改動,感覺挺不錯的。官網上給的樣例非常easy,以下改進了一點,實現了歷史消息的推送。

demo地址:chat.codeboy.me


當中server端代碼:

var app = require(‘express‘)();
var http = require(‘http‘).Server(app);
var io = require(‘socket.io‘)(http);
var history = new Array();

app.get(‘/‘, function(req, res){
  res.sendfile(‘chat.html‘);
});

io.on(‘connection‘, function(socket){
  socket.on(‘chat message‘, function(msg){
    io.emit(‘chat message‘, msg);
    addMsg(msg);
  });

  socket.on(‘login message‘, function(msg){
    socket.join(‘history room‘);
    for(var i=0;i<history.length;i++){
      io.in(‘history room‘).emit(‘chat message‘, history[i]);
   }
      io.in(‘history room‘).emit(‘chat message‘, ‘lyd__上面是近期的一些信息‘);
    socket.leave(‘history room‘);
    socket.join(‘chat room‘); 
 
    io.emit(‘chat message‘,msg);
    addMsg(msg);
  });
});

http.listen(3000, function(){
  console.log(‘listening on *:3000‘);
});

function addMsg(msg){
 history.push(msg);
 if(history.length>100)
    history.shift();
};


聊天頁面代碼:

<!doctype html>
<html>
  <head>
    <title>聊天室</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 20px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%;  }
      form button { width: 10%; background: rgb(130, 224, 255); border: none;  padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px 5px 10px; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button id="btn">登錄</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      var socket = io();
      var login  =true;
      var username = "" ; 
      var myDate = new Date();
      $(‘form‘).submit(function(){
         if(login){
           username = $(‘#m‘).val();
           if(username.length==0){
               alert("請輸入用戶名");
               return false;
            }
           login = false ;
           socket.emit(‘login message‘, "lyd__<font color=blue>"+username + ‘</font>增加了聊天室   ‘+myDate.getMonth()+"-"+myDate.getDate()+" "+myDate.getHours()+":"+myDate.getMinutes()+":"+myDate.getSeconds());
           $(‘#btn‘).html("發送");
         }else { 
           socket.emit(‘chat message‘, username +"##"+ $(‘#m‘).val());
        }
         $(‘#m‘).val(‘‘);
        return false;
      });
        socket.on(‘chat message‘, function(msg){
        var item = msg.split("##",2);
        if(msg.indexOf(‘lyd__‘)==0)
          $(‘#messages‘).append(‘<li style="text-align:center; font-size:12px;margin-top:1px; color:red; background-color:#eee;">‘ +msg.substr(5)+‘</li>‘);
        else if(msg.indexOf(username)==0){
          $(‘#messages‘).append(‘<li style="text-align:right; font-size:12px; color:red;">‘+item[0]+‘:</li>‘);
          $(‘#messages‘).append(‘<li style="text-align:right;padding-top:0px; padding-left:30%;color:purple;">‘+item[1]+‘</li>‘);
        }else {
          $(‘#messages‘).append(‘<li style="text-align:left;font-size:12px; color:red;">‘+item[0]+‘:</li>‘);
          $(‘#messages‘).append(‘<li style="text-align:left;padding-top:0px; padding-right:30%; color:purple;">‘+item[1]+‘</li>‘);
        }
      });
    </script>
  </body>
</html>

這樣就實現了一個聊天室,進入後輸入username,登錄,之後server返回近期的100條消息。

nodejs即時聊天