美文网首页
基于express和socket.io实现的简单聊天室

基于express和socket.io实现的简单聊天室

作者: McRay | 来源:发表于2017-03-12 18:34 被阅读0次

    最近在学nodejs的时候,自己结合所学的知识运用了nodejs的框架express和socket.io实现了下面简单的聊天室

    先看一下测试的截图:

    服务器端.PNG

    git bash下输入node app.js建立起服务器

    浏览器端.PNG

    然后再浏览器上输入localhost:3000地址,输入名字之后就能进入聊天室。

    html代码:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>chat-room</title>
        <link rel="stylesheet" type="text/css" href="css/main.css">
        <script src="javascripts/jquery.min.js"></script>
        <script src="/socket.io/socket.io.js"></script>
        <script src="javascripts/chat.js"></script>
    </head>
    <body>
      <div class="contaniner">
          <h1>Socket.io - Simple chat room</h1>
          <div class="onlinepeople">
          </div>
          <div id="content"></div>
          <div class="input">
            <span id="status">Connecting...</span>
            <input type="text" id="input" />
          </div>
      </div>
    </body>
    </html>
    

    css代码:

    * {padding:0px; margin:0px;}
    body{font-family:tahoma; font-size:12px;margin:10px;}
    p {line-height:18px;padding:2px;}
    div {width:500px;}
    .contaniner{
        width:600px;
        height:600px;
        border:1px solid #888;
        margin:0 auto;
    }
    .contaniner h1{
        text-align: center;
    }
    #content {
        overflow: scroll;
        width:80%;
        margin:0 auto;
        height:70%;
        padding:5px;
        background:#ddd;
        border-radius:5px;
        border:1px solid #CCC;
        margin-top:10px;
    }
    .input{
        padding-left:50px;
        height:10%;
        width:100%;
        margin:0 auto;
    }
    #input {
        border-radius:2px;
        border:1px solid #ccc;
        margin-top:10px;
        padding:5px;
        width:380px;
    }
    #status {
        text-align: center;
        width:100px;
        display:block;
        float:left;
        margin-top:15px;
    }
    

    服务器端:

    /**
     * Created by 佳锐 on 2017/3/10.
     */
    //使用express快速搭建web服务器
    var express = require('express');
    var path = require('path');
    var app = express();
    var server = require('http').createServer(app);
    //使用socket.io监听事件
    var io = require('socket.io').listen(server);
    
    //对express配置时,从express3迁移到4的一些改变
    var favicon = require('serve-favicon');
    var logger = require('morgan');
    var bodyParser = require('body-parser');
    var multer = require('multer');
    var methodOverride = require('method-override');
    var errorHandler = require('errorhandler');
    
    //设置日志级别
    io.set('log level',1);
    //在线人数
    var onlineCount = 0;
    //历史信息容器
    var historyContent = [];
    
    //socket监听连接事件
    io.on('connection',function(socket){
        socket.emit('onlinepeople',onlineCount);
        socket.emit('historyContentDisplay',historyContent);
        onlineCount++;
        socket.emit('open');//通知客户端已连接
        //打印握手信息
        //console.log(socket.handshake);
    
        //构造客户端对象
        var client = {
            socket:socket,
            name:false,
            color:getColor()
        }
    
        //对message事件的监听
        socket.on('message',function(msg){
            //console.log("111");
            var obj = {
                time:getTime(),
                color:client.color
            };
            //判断是不是第一次连接,以第一条信息作为用户名
            if(!client.name){
                client.name = msg;
                obj['text']=client.name;
                obj['author']='System';
                obj['type']='welcome';
                console.log(client.name+'login');
    
                //返回欢迎语
                //触发事件,返回给客户端
                socket.emit('system',obj);
                //广播新用户登录
                socket.broadcast.emit('system',obj);
                //触发客户端的onlinepeople事件
                socket.emit('onlinepeople',onlineCount);
            }else{
                //如果不是第一次的连接,正常的聊天消息
                obj['text']=msg;
                obj['author']=client.name;
                obj['type']='message';
                console.log(client.name+'say:'+msg);
                //返回消息
                //触发事件
                socket.emit('message',obj);
                //广播向其他用户发消息
                socket.broadcast.emit('message',obj);
            }
            //console.log(client.name);
            console.log("在线人数:"+onlineCount);
            historyContent.push({
               'author':obj['author'],
                'time':obj['time'],
                'msg':msg,
                'type':obj['type']
            });
            console.log(historyContent);
        });
        //监听退出事件
        socket.on('disconnect',function(){
            onlineCount--;
           var obj = {
             time:getTime(),
               color:client.color,
               author:'System',
               text:client.name,
               type:'disconnect'
           };
            historyContent.push({
                'author':obj['author'],
                'time':obj['time'],
                'msg':obj['text'],
                'type':obj['type']
            });
    
           //广播用户已退出
            socket.broadcast.emit('system',obj);
            console.log(client.name+'Disconnect');
        });
    });
    //express基本配置
    app.set('port',process.env.PORT || 3000);
    app.set('views',__dirname+'/views');
    // app.use(favicon(__dirname + '/public/favicon.ico'));
    app.use(logger('dev'));
    app.use(bodyParser());
    app.use(methodOverride());
    //使用express发送css js等静态资源
    app.use(express.static(path.join(__dirname, 'public')));
    
    if ('development' == app.get('env')) {
        app.use(errorHandler());
    }
    
    //指定websocket的客户端的html文件
    //express获得get请求时将chat.html文件返回给浏览器
    app.get('/',function(req,res){
        res.sendfile('views/chat.html');
    });
    //服务器监听端口
    server.listen(app.get('port'), function(){
        console.log("Express server listening on port " + app.get('port'));
    });
    
    var getTime=function() {
        var date = new Date();
        return date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
    };
    
    var getColor=function(){
        var colors = ['aliceblue','antiquewhite','aqua','aquamarine','pink','red','green',
            'orange','blue','blueviolet','brown','burlywood','cadetblue'];
        return colors[Math.round(Math.random() * 10000 % colors.length)];
    };
    

    首先使用express快速搭建web服务器

    var express = require('express');
    var path = require('path');
    var app = express();
    var server = require('http').createServer(app);
    

    然后使用socket.io监听服务器

    var io = require('socket.io').listen(server);
    

    进行express的配置过程中,因为我的版本是express3,最新版本是express4,所以需要做一定的迁移步骤,具体如下

    var favicon = require('serve-favicon');
    var logger = require('morgan');
    var bodyParser = require('body-parser');
    var multer = require('multer');
    var methodOverride = require('method-override');
    var errorHandler = require('errorhandler');
    
    app.set('port',process.env.PORT || 3000);
    app.set('views',__dirname+'/views');
    // app.use(favicon(__dirname + '/public/favicon.ico'));
    app.use(logger('dev'));
    app.use(bodyParser());
    app.use(methodOverride());
    //使用express发送css js等静态资源
    app.use(express.static(path.join(__dirname, 'public')));
    
    if ('development' == app.get('env')) {
        app.use(errorHandler());
    }
    

    socket监听连接事件


    客户端代码:

    /**
     * Created by 佳锐 on 2017/3/10.
     */
    $(function(){
        var content = $('#content');
        var status = $('#status');
        var input = $('#input');
        var online = $('.onlinepeople');
        var myName = false;
    
        //建立websocket连接
        socket = io.connect('http://localhost:3000');
        //收到server的连接确认
        socket.on('open',function(){
            status.text('Choose a name:');
        });
    
        //监听system事件,判断welcome或者disconnect,打印系统消息信息
        socket.on('system',function(json){
            var p = '';
            if (json.type === 'welcome'){
                if(myName == json.text) status.text(myName + ': ').css('color', json.color);
                p = '<p style="background:'+json.color+'">system @ '+ json.time+ ' : Welcome ' + json.text +'</p>';
            }else if(json.type == 'disconnect'){
                p = '<p style="background:'+json.color+'">system @ '+ json.time+ ' : Bye ' + json.text +'</p>';
            }
            content.prepend(p);
        });
    
        socket.on('onlinepeople',function(onlineCount){
               online.text('');
                var  p = '<h2 style="margin-left:50px;">在线人数:'+onlineCount+'</h2>';
                online.prepend(p);
        });
    
        socket.on('historyContentDisplay',function(historyConten){
            if(historyConten.length != 0) {
                for (var i = 0; i < historyConten.length; i++) {
                    if(historyConten[i].type == 'welcome'){
                        var p = '<p><span style="color:'+historyConten[i].color+';">' + historyConten[i].author+'</span> @ '+ historyConten[i].time+ ' : Welcome '+historyConten[i].msg+'</p>';
                        content.prepend(p);
                    } else if(historyConten[i].type == 'disconnect'){
                        var p = '<p><span style="color:'+historyConten[i].color+';">' + historyConten[i].author+'</span> @ '+ historyConten[i].time+ ' : Bye'+historyConten[i].msg+'</p>';
                        content.prepend(p);
                    } else{
                        var p = '<p><span style="color:'+historyConten[i].color+';">' + historyConten[i].author+'</span> @ '+ historyConten[i].time+ ' : '+historyConten[i].msg+'</p>';
                        content.prepend(p);
                    }
                }
                return;
            } else{
                return;
            }
        });
        //发送事件到服务端
        //监听message事件,打印消息信息
        socket.on('message',function(json){
            var p = '<p><span style="color:'+json.color+';">' + json.author+'</span> @ '+ json.time+ ' : '+json.text+'</p>';
            content.prepend(p);
        });
    
        //通过“回车”提交聊天信息
        input.keydown(function(e){
            if(e.keyCode == 13){
                var msg = $(this).val();
                if(!msg){
                    return;
                }
                socket.send(msg);//将msg发送到服务器端
                $(this).val('');
                if(myName === false){
                    myName = msg;
                }
            }
        });
    });
    

    代码的地址:https://github.com/McRayFE/chat-room

    相关文章

      网友评论

          本文标题:基于express和socket.io实现的简单聊天室

          本文链接:https://www.haomeiwen.com/subject/xrotnttx.html