1

一.要点分析

(1) 对于socket.io,它是基于事件响应的socket,可以进行长时间的消息传递。其服务端使用的方法主要不过就是两个,on()和emit()

io.on('connetcion',function(socket) {
    socket.on('event',function(data) {
        /*执行相应的方法*/
        //通知客户端执行事件
        socket.emit('new event',{data:'mydata'});
    });
});

(2)搭建好服务器端后就进行客户端连接


//引入socket
var socket = io();

socket.on('event',function(data) {
    /*执行事件*/    
    //通知服务器端执行事件
    socket.emit('new event',{data:'mydata'});
});

(3)接下来就是对视图的搭建

二.源代码和注释分析

(1) app.js:

//引入express框架
var express = require('express');
var app = express();

//服务端创建
var server = require('http').createServer(app);
//使用socket.io进行通信
var io = require('socket.io')(server);
var port = process.env.POST || 8000;

//服务开启
server.listen(port,function() {
    console.log("The chatting room is running at port: " + port);
});

//使用静态文件目录
app.use(express.static(__dirname + '/public'));

//当前进入聊天室的人数
var usersNumber = 0;

//客户端通过socket链接服务端
io.on('connection',function(socket) {
    //默认没有用户进入
    var addUser = false;
    
    //客户端发送新的消息
    socket.on('new message',function(data) {
        //广播所有在线客户端新消息的产生
        socket.broadcast.emit('new message',{
            userName: socket.userName,
            message: data
        });
    });
    //客户端发送有用户加入的消息
    socket.on('add user',function(userName) {
        if(addUser) return;
        socket.userName = userName;
        usersNumber++;
        addUser=true;
        //向客户端发送登陆成功
        socket.emit('login',{
            userName: socket.userName,
            usersNumber:usersNumber
        });
        //广播有新用户加入
        socket.broadcast.emit('new user join',{
            userName:socket.userName,
            usersNumber:usersNumber
        });
    });
    //客户端断开链接
    socket.on('disconnect',function() {
        if(addUser) {
            usersNumber--;
            //通知所有客户端有用户离开
            socket.broadcast.emit('user left',{
                userName:socket.userName,
                usersNumber:usersNumber
            });
        }
    });
});

(2) main.js:

$(function(){
    //创建socket与服务端链接
    var socket = io();
    //通过jquery获取dom节点
    var $logPage = $('.logPage');
    var $logList = $('.logList');
    var $chatPage = $('.chatPage');
    var $messageContent = $('.messageContent');
    var $messageList = $('.messageList');
    var $messageInput = $('.messageInput');
    var $usernameInput = $('.usernameInput');
    var $sendMessage = $('.sendMessage');
    var $addUser = $('.addUser');
    var $loginPage = $('.loginPage');
    var $messageInputBar = $('.messageInputBar');

    //默认当前登陆输入框为焦点状态
    var $currentInput = $usernameInput.focus();

    //用于记录当前的用户名
    var userName;
    var connect = false;

    //监听服务器是否有新的消息产生,有的话就显示消息到列表
    socket.on('new message',function(data) {
        //在列表框中添加消息,类型为收取的消息
        addNewMessage(data,2);
    });

    //监听服务器是否登陆成功,成功就显示成功登陆
    socket.on('login',function(data) {
        userLogin(data);
    });

    //监听服务器是否有新的用户加入,有的话就显示
    socket.on('new user join',function(data) {
        newUserJoin(data);
    });

    //监听服务器是否有用户离开
    socket.on('user left',function(data){
        userLeft(data);
    });


    function userLogin(data) {
        //登陆成功,输出信息
        connect = true;
        $logList.empty();
        $logList.append('<li><p>Name: ' + data.userName + ' is joined</p><li>');
        $logList.append('<li><p>CurrentNumber: ' + data.usersNumber + '</p></li>');
    }


    function addNewMessage(data,state) {
        if(state == 1) {
            $messageList.append(
            '<div class="aui-chat-item aui-chat-right"><div class="aui-chat-inner"><div class="aui-chat-name">' + data.userName +'</div><div class="aui-chat-content">'+data.message+'</div></div></div>');
        }else {
            $messageList.append(
            '<div class="aui-chat-item aui-chat-left"><div class="aui-chat-inner"><div class="aui-chat-name">' + data.userName +'</div><div class="aui-chat-content">'+data.message+'</div></div></div>');
        }
    }

    function newUserJoin(data) {
        $logList.empty();
        $logList.append('<li><p>Name: ' + data.userName + ' is joined</p></li>');
        $logList.append('<li><p>CurrentNumber: ' + data.usersNumber + '</p></li>');
    }

    function userLeft(data) {
        $logList.empty();
        $logList.append('<li><p>User: ' + data.userName + ' has left</p><li>');
        $logList.append('<li><p>CurrentNumber: ' + data.usersNumber + '</p></li>');
    }

    //当用户点击发送消息时的事件
    $sendMessage.click(function(event) {
        /* Act on the event */
        var message = $messageInput.val();
        if (message && connect) {
      $messageInput.val('');
      addNewMessage({
        userName: userName,
        message: message
      },1);
      socket.emit('new message', message);
    }
    });    

    //当用户点击登陆事件
    $addUser.click(function(event) {
        /* Act on the event */
        userName = $usernameInput.val().trim();
        if (userName) {
      $loginPage.fadeOut();
      $chatPage.show();
      $messageInputBar.show();
      $loginPage.off('click');
      $currentInput = $messageInput.focus();
      socket.emit('add user', userName);
    }
    });

});

(3) index.html:

<!doctype html>
<html>
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="./css/aui.2.0.css">
    <style type="text/css" media="screen">
        * {
            font-family: 'Microsoft Yahei';
        }
        .header {
            position: fixed;
        }
        .content {
            padding-top: 2rem;/*有顶部固定导航条时设置*/ padding-bottom: 5rem;/*有底部固定导航条时设置*/
        }
        .chatPage {
            display: none;
        }
        .logPage {
            background-color:#00FFFF;
            border-radius: .2rem;
        }
        .messageInputBar {
            display: none;
        }
            .chatItem {

            }
    </style>
    </head>
    <body>
        <header class="aui-bar aui-bar-nav header">Chatting Room</header>
        <div class="aui-content-padded content">
            <section class="logPage">
                <div class="">
                    <ul class="logList"></ul>
                </div>
            </section>
            <div class="chatPage aui-content">
                <section class="aui-chat messageList">
                </section>
            </div>
            <div class="loginPage">
                <div>Please input your name</div>
                <div class="aui-row">
                    <div class="aui-col-xs-9">
                        <input type="text" placeholder="Username" class="usernameInput">
                    </div>
                    <div class="aui-col-xs-3">
                        <div class="aui-btn aui-btn-primary addUser">Login</div>
                    </div>
                </div>
            </div>
        </div>
        <footer class="messageInputBar aui-bar aui-bar-tab aui-padded-l-15">
            <div class="aui-bar-tab-item">
                <input type="text" placeholder="Message" class="messageInput">
            </div>
            <div class="aui-bar-tab-item">
                <div class="aui-btn aui-btn-primary sendMessage">Send</div>
            </div>
        </footer>
    </body>
    <script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
    <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="./js/main.js"></script>
</html>

(4) 使用aui视图框架

github仓库链接
聊天室链接


lgybetter
200 声望8 粉丝

花式编码