NodeJS 實戰(二) - 聊天室②

上一博文 NodeJS 實戰(二) - 聊天室① 介紹和實現聊天室靜態資源的架構, 這一次來加入真正的實時聊天功能吧。javascript

 

在server.js須要加入新的模塊,後續會來定義這個模塊,這個模塊是基於socket.io主要是用來支持html

var chatServer = require('./lib/chat_server');
chatServer.listen(server)

 

在lib文件夾裏來定義這個模塊(chat_server.js)吧java

首先引用nodejs socket.io 模塊node

var socketio = require('socket.io');
var io;
var guestNumber = 1;
var nickNames = {};
var namesUsed = [];
var currentRoom = {};

 關鍵代碼的加入架構

exports.listen = function(server) {
    io = socketio.listen(server); //啓動socketio監聽
    io.set('log level', 1);
    io.sockets.on('connection', function (socket) {
        guestNumber = assignGuestName(socket, guestNumber,
            nickNames, namesUsed);//初始化新加入用戶名稱
        handleMessageBroadcasting(socket, nickNames);//處理用戶發送的消息
        socket.on('rooms', function() {
            socket.emit('rooms', io.sockets.manager.rooms);
        });
    });
};

 

//設置新的guestName
function assignGuestName(socket, guestNumber, nickNames, namesUsed) {
    var name = 'Guest' + guestNumber;
    nickNames[socket.id] = name;
    socket.emit('nameResult', {
        success: true,
        name: name
    });
    namesUsed.push(name);
    return guestNumber + 1;
}

//處理消息function
function handleMessageBroadcasting(socket) {
    socket.on('message', function (message) {
        socket.broadcast.to(message.room).emit('message', {
            text: nickNames[socket.id] + ': ' + message.text
        });
    });
}

在javascript目錄里加入前臺js  chat.jsapp

var Chat = function(socket) {
    this.socket = socket;
};

//消息處理方法
Chat.prototype.sendMessage = function(room, text) {
    var message = {
        room: room,
        text: text
    };
    this.socket.emit('message', message);
};

在javascript目錄里加入前臺js  chat_ui.jssocket

function divEscapedContentElement(message) {
    return $('<div></div>').text(message);
}
function divSystemContentElement(message) {
    return $('<div></div>').html('<i>' + message + '</i>');
}

function processUserInput(chatApp, socket) {
    var message = $('#send-message').val();
    var systemMessage;
    if (message.charAt(0) == '/') {
        systemMessage = chatApp.processCommand(message);
        if (systemMessage) {
            $('#messages').append(divSystemContentElement(systemMessage));
        }
    } else {
        chatApp.sendMessage($('#room').text(), message);
        $('#messages').append(divEscapedContentElement(message));
        $('#messages').scrollTop($('#messages').prop('scrollHeight'));
    }
    $('#send-message').val('');
}

var socket = io.connect();
$(document).ready(function() {
    var chatApp = new Chat(socket);
    socket.on('nameResult', function(result) {
        var message;
        if (result.success) {
            message = 'You are now known as ' + result.name + '.';
        } else {
            message = result.message;
        }
        $('#messages').append(divSystemContentElement(message));
    });
    socket.on('joinResult', function(result) {
        $('#room').text(result.room);
        $('#messages').append(divSystemContentElement('Room changed.'));
    });
    socket.on('message', function (message) {
        var newElement = $('<div></div>').text(message.text);
        $('#messages').append(newElement);
    });
    socket.on('rooms', function(rooms) {
        $('#room-list').empty();
        for(var room in rooms) {
            room = room.substring(1, room.length);
            if (room != '') {
                $('#room-list').append(divEscapedContentElement(room));
            }
        }
        $('#room-list div').click(function() {
            chatApp.processCommand('/join ' + $(this).text());
            $('#send-message').focus();
        });
    });
    setInterval(function() {
        socket.emit('rooms');
    }, 1000);
    $('#send-message').focus();
    $('#send-form').submit(function() {
        processUserInput(chatApp, socket);
        return false;
    });
});

最後記得在index.html裏引用這2個js 前一篇有提到過post

好了,,, node server.js 吧ui

最簡單的聊天室能夠聊天了this

相關文章
相關標籤/搜索