Node JS Socket IO Chat问题

时间:2013-04-26 05:57:07

标签: javascript node.js socket.io chat

我正在使用节点js和socket .io

开发一对一的聊天应用程序

但是当我尝试运行我的chat.html时,它会出现错误“引用错误io未定义”。

我搜索了这个问题,我找到了一个解决方案,它说使用cdn,我也试过了。但这次错误不同是“找不到方法连接”

socket.io.js位于node_modules \ socket.io \ lib

当我试图通过浏览器访问它时说“无法获取socket.io.js”

这里我粘贴了我的代码。请帮帮我

Server.js

var app = require('express').createServer();
var io = require('socket.io').listen(app);
var fs = require('fs');

app.listen(8080);


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


var usernames = {};

function check_key(v) {
    var val = '';

    for (var key in usernames) {
        if (usernames[key] == v)
            val = key;
    }
    return val;
}

io.sockets.on('connection', function (socket) {


    socket.on('sendchat', function (data) {

        io.sockets.emit('updatechat', socket.username, data);
    });


    socket.on('adduser', function (username) {

        socket.username = username;

        usernames[username] = socket.id;

        socket.emit('updatechat', 'SERVER', 'you have connected');

        socket.emit('store_username', username);

        socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected: ' + socket.id);

        io.sockets.emit('updateusers', usernames);
    });


    socket.on('disconnect', function () {

        delete usernames[socket.username];

        io.sockets.emit('updateusers', usernames);

        socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
    });


    socket.on('check_user', function (asker, id) {

        io.sockets.socket(usernames[asker]).emit('msg_user_found', check_key(id));
    });


    socket.on('msg_user', function (usr, username, msg) {

        io.sockets.socket(usernames[usr]).emit('msg_user_handle', username, msg);

        fs.writeFile("chat_data.txt", msg, function (err) {
            if (err) {
                console.log(err);
            }
        });
    });


});

Chat.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="/socket.io/socket.io.js "></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
    <script type="text/javascript">
        var my_username = '';
        try {
            function send_individual_msg(id) {

                socket.emit('check_user', my_username, id);

            }

            var socket = io.connect('http://localhost:8008');


            socket.on('connect', function () {

                socket.emit('adduser', prompt("What's your name?"));
            });


            socket.on('msg_user_handle', function (username, data) {
                $('#conversation').append('<b>' + username + ':</b> ' + data + '<br>');
            });


            socket.on('msg_user_found', function (username) {

                socket.emit('msg_user', username, my_username, prompt("Type your message:"));
            });


            socket.on('updatechat', function (username, data) {
                $('#conversation').append('<b>' + username + ':</b> ' + data + '<br>');
            });


            socket.on('store_username', function (username) {
                my_username = username;
            });


            socket.on('updateusers', function (data) {

                $('#users').empty();
                $.each(data, function (key, value) {
                    $('#users').append('<div style="cursor:pointer;" onclick="send_individual_msg(\'' + value + '\')">' + key + '</div>');
                });
            });


            $(function () {

                $('#datasend').click(function () {
                    var message = $('#data').val();
                    if (message == '' || jQuery.trim(message).length == 0)
                        return false;
                    $('#data').val('');

                    socket.emit('sendchat', message);
                });


                $('#data').keypress(function (e) {
                    if (e.which == 13) {
                        $(this).blur();

                        $('#datasend').click();
                    }
                });
            });
        }
        catch (err) {
            alert(err);
        }

    </script>
</head>
<body>
    <div style="float: left; width: 100px; border-right: 1px solid black; height: 300px;
        padding: 10px; overflow: scroll-y;">
        <b>USERS</b>
        <div id="users">
        </div>
    </div>
    <div style="float: left; width: 550px; height: 250px; overflow: scroll-y; padding: 10px;">
        <div id="conversation">
        </div>
        <input id="data" style="width: 200px;" />
        <input type="button" id="datasend" value="send" />
    </div>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

由于您使用的是Express,因此应将客户端的socket.io.js文件放在

public/javascripts 

并在HTML文件中,文件的路径为:

javascripts/socket.io.js

答案 1 :(得分:0)

由于您使用的是静态文件,即socketio.js,您需要使用

//For including static files in expressJS
app.use(express.static(__dirname + '/'));

Express提供了一个内置的中间件express.static来提供静态文件,如图像,CSS,JavaScript等。

您只需将保存静态资产的目录名称传递给express.static中间件即可直接开始提供文件。例如,如果将图像,CSS和JavaScript文件保存在名为public的目录中,则可以执行此操作 -

app.use(express.static('public'));

将/socket.io/socket.io.js放在公共目录