与nodejs和mongodb实时聊天

时间:2014-03-05 12:50:50

标签: javascript node.js mongodb

所以,我创建了一个简单的聊天系统,它由nodeJS和mongodb组成。我目前在apache上“托管”它,它在我的计算机上完美运行,但如果其他人连接到本地网络上的我的站点,则聊天无法正常工作。发送消息和显示消息功能中断。

Ps:代码来自phpacademy,所以对他们有所帮助。

这是我使用的代码:

HTML:

<!DOCTYPE html>
<html>

    <head>
        <title>ChattSystem</title>
        <link rel="stylesheet" href="css/main.css">
    </head>

    <body>
        <div class="chat">
            <input type="text" class="chat-name" placeholder="Enter your name">
            <div class="chat-messages"></div>

            <textarea placeholder="Type your message"></textarea>
            <div class="chat-status">Status: <span>Idle</span></div>
        </div>

        <script src="http://127.0.0.1:8080/socket.io/socket.io.js"></script>


        <script>
            (function() {
                var getNode = function(s) {
                    return document.querySelector(s);
                },

                // Get required nodes
                status = getNode('.chat-status span'),
                messages = getNode('.chat-messages'),
                textarea = getNode('.chat textarea'),
                chatName = getNode('.chat-name');

                statusDefault = status.textContent,

                setStatus = function(s) {
                    status.textContent = s;

                    if(s !== statusDefault) {
                        var delay = setTimeout(function() {
                            setStatus(statusDefault);
                            clearInterval(delay);
                        }, 3000);   
                    }
                };


                try {
                    var socket = io.connect('http://127.0.0.1:8080');
                } catch(e) {
                    // Set status to warn user
                }

                if(socket !== undefined) {

                    // Listen for output
                    socket.on('output', function(data) {
                        if(data.length) {
                            // Loop through results
                            for(var x = 0; x < data.length; x = x + 1) {
                                var message = document.createElement('div');

                                message.setAttribute('class', 'chat-message');
                                message.textContent = data[x].name + ': ' + data[x].message;

                                // Append
                                messages.appendChild(message);
                                messages.insertBefore(message, messages.firstChild);
                            }
                        }
                    });

                    // Listen for a status
                    socket.on('status', function(data) {
                        setStatus((typeof data === 'object') ? data.message : data);

                        if(data.clear === true) {
                            textarea.value = '';
                        }
                    });

                    // Listen for keydown
                    textarea.addEventListener('keydown', function(event) {
                        var self = this,
                            name = chatName.value;

                        if(event.which);if(event.which == 13 && event.shiftKey === false) {
                            socket.emit('input', {
                                name: name,
                                message: self.value
                            });

                            event.preventDefault();
                        }
                    });

                }

            })();
        </script>
    </body>

</html>

Server.js

var mongo = require('mongodb').MongoClient,
    client = require('socket.io').listen(8080).sockets;

mongo.connect('mongodb://127.0.0.1/chat', function(err, db) {
    if(err) throw err;

    client.on('connection', function(socket) {

        var col = db.collection('messages'),
            sendStatus = function(s) {
                socket.emit('status', s);
            };

        // Emit all messages
        col.find().limit(100).sort({_id: 1}).toArray(function(err, res) {
            if(err) throw err;
            socket.emit('output', res);
        });

        // Wait for input
        socket.on('input', function(data) {
            var name = data.name,
                message = data.message,
                whitespacePattern = /^\s*$/;

            if(whitespacePattern.test(name) || whitespacePattern.test(message)) {
                sendStatus('Name and message is required.');
            } else {
                col.insert({name: name, message: message}, function() {

                    // Emit latest message to ALL qclients
                    client.emit('output', [data]);

                    sendStatus({
                        message: "Message sent",
                        clear: true
                    });
                }); 
            }

        });

    });
});

1 个答案:

答案 0 :(得分:0)

在客户端的JS中,将IP更改为您的服务器IP .. 您的脚本当前具有相同的本地IP,这意味着始终在localhost ...

找到您的IP并将其放入:

HTML(JS客户端)

try {
   var socket = io.connect('http://192.168.x.x:8080');
} catch(e) {
   // Set status to warn user
}