【问题标题】:What is the best method for socket.io + express session support?socket.io + express session 支持的最佳方法是什么?
【发布时间】:2015-01-29 00:40:03
【问题描述】:

我是 node.js 的新手,我似乎找不到创建可以从 express 和 socket.io 交互的会话的好方法。我尝试了许多发布的解决方案,但似乎没有一个有效。任何建议将不胜感激。

谢谢!

【问题讨论】:

    标签: node.js session express socket.io


    【解决方案1】:

    我可以提供您正在使用的确切代码 sn-p 吗?我能够从示例中获得一个基本的聊天应用程序和多人游戏以从节点运行,并查看您尝试使用的示例。

    简而言之,您需要为 io 建立一个变量以要求 sockets.io 模块。从那里您还需要在您的 app.js 文件中写入要发送和接收的所有潜在套接字消息。我是从Michael Mukhin's Chat tutorial: 拿来的

    安装 Node 后,为您的应用创建一个新文件夹并创建一个名为 package.json 的空白文件。 Node.JS 读取此文件以确定运行应用程序所需的依赖项。在这个 package.json 文件中复制以下内容:

    {
     "name": "mukhin_chat",
     "description": "example chat application with socket.io",
     "version": "0.0.1",
     "dependencies": {
        "express": "2.4.6",
        "socket.io": "0.8.4"
     }
    

    }

    现在返回命令行并键入“npm install”以包含 express 和 socket.io。创建一个名为 app.js 的第二个文件并使用以下内容:

    var app = require('express').createServer()
    var io = require('socket.io').listen(app);
    
    app.listen(8080);
    
    // routing
    app.get('/', function (req, res) {
      res.sendfile(__dirname + '/index.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 parameters
            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');
        });
    });
    

    最后,创建面向客户端的 index.html 文件,该文件将运行并显示给连接到您的应用的用户:

    <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 socket = io.connect('http://localhost:8080');
    
        // 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>
    <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>
    

    使用 node app.js 运行服务器本身

    在命令提示符窗口中。

    关键要点:

    1. 使用全局“io”声明所有潜在的 sockets.io 活动 变量。
    2. socket.action = 更新特定套接字
    3. sockets.action = 更新所有套接字。
    4. 名字中有io,意思是sockets只有两个值,on 或 off 因此将 socket.on 视为类型以“触发”函数。
    5. 查看 app.js(服务器端数据)如何为各种“socket.on”条件定义不同的函数?这就是套接字连接到您的 index.html 蚂蚁与您的应用程序用户交谈的方式。 (客户端数据)

    HTH

    【讨论】:

    • 感谢您分享您的代码。建议如果您可以更新 expressJS 4.x 的代码会很好,因为您使用的 "express": "2.4.6" 版本太旧了。请使用从不版本。从那时起,许多事情都发生了变化。如果您使用 Express 4.9 写作,那将是最好的,谢谢。
    • 请务必澄清这一点:不是我的代码,迈克尔的 :)
    猜你喜欢
    • 2018-04-26
    • 2013-12-02
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    相关资源
    最近更新 更多