2

我正在开发一个我想与 websocket 交互一起使用的应用程序。我使用了基于 node.js 和 socket.io 的服务器和简单的聊天页面作为我页面的起点。我正在修改并弄清楚服务器和 html 页面之间的交互。

编写基本聊天页面的人在 html 页面上使用内联 javascript 作为聊天的客户端,所以我将其分解为自己的 javascript 文件,没什么大不了的。

问题是我想使用本地机器上的 html 和关联的 javascript 文件来连接到我在 web 服务器上创建的 node.js 服务器。他的设置是访问 web-server 上的 html 页面,该页面与作为 web-socket 服务器的 server.js 文件位于同一文件夹中。

我试图弄清楚如何让客户端javascript文件在页面打开时开始做这件事(我猜需要一个加载事件),以及如何设置它来调用网络服务器javascript文件。

我要把他的代码贴在这里,不是我的,我只是用他的教程制作了chat.html和server.js。基本上是复制粘贴。

一如既往地非常感谢任何帮助或指导。

------------------chat.html--------------

<!doctype html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>WebSocket Chat</title>
        <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>
            var URL = window.location.protocol + "//" + window.location.host;
            console.log("Connecting to " + URL);
            var socket = io.connect(URL);
            // on connection to server, ask for user's name with an anonymous callback
            socket.on('connect', function() {
                // call the server-side function 'adduser' and send one parameter (value of prompt)
                socket.emit('adduser', prompt("What's your name?"));
            });
            // listener, whenever the server emits 'updatechat', this updates the chat body
            socket.on('updatechat', function(username, data) {
                $('#conversation').append('<b>' + username + ':</b> ' + data + '<br>');
            });
            // listener, whenever the server emits 'updateusers', this updates the username list
            socket.on('updateusers', function(data) {
                $('#users').empty();
                $.each(data, function(key, value) {
                    $('#users').append('<div>' + key + '</div>');
                });
            });
            // on load of page
            $(function() {
                // when the client clicks SEND
                $('#datasend').click(function() {
                    var message = $('#data').val();
                    $('#data').val('');
                    // tell server to execute 'sendchat' and send along one parameter
                    socket.emit('sendchat', message);
                });
                // when the client hits ENTER on their keyboard
                $('#data').keypress(function(e) {
                    if (e.which == 13) {
                        $(this).blur();
                        $('#datasend').focus().click();
                    }
                });
            });
        </script>

    </head>
    <body>
        <h1>WebSocket Chat</h1>
        <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:300px;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>

----------server.js-------------- ---

var port = 5000;
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);

console.log("Listening on port " + port);
server.listen(port);

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

// usernames which are currently connected to the chat
var usernames = {};

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

    // when the client emits 'sendchat', this listens and executes
    socket.on('sendchat', function (data) {
        // we tell the client to execute 'updatechat' with 2 parameter
        io.sockets.emit('updatechat', socket.username, data);
    });

    // when the client emits 'adduser', this listens and executes
    socket.on('adduser', function(username){
        // we store the username in the socket session for this client
        socket.username = username;
        // add the client's username to the global list
        usernames[username] = username;
        // echo to client they've connected
        socket.emit('updatechat', 'SERVER', 'you have connected');
        // echo globally (all clients) that a person has connected
        socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
        // update the list of users in chat, client-side
        io.sockets.emit('updateusers', usernames);
    });

    // when the user disconnects.. perform this
    socket.on('disconnect', function(){
        // remove the username from global usernames list
        delete usernames[socket.username];
        // update list of users in chat, client-side
        io.sockets.emit('updateusers', usernames);
        // echo globally that this client has left
        socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
    });
});
4

0 回答 0