socket.io + express session支持的最佳方法是什么?

时间:2014-12-01 03:01:34

标签: node.js session express socket.io

我是node.js的新手,我似乎无法找到一个很好的方法来创建一个可以通过express和socket.io进行交互的会话。我已经尝试了许多解决方案,但似乎都没有。任何建议都将不胜感激。

谢谢!

1 个答案:

答案 0 :(得分:0)

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

简而言之,您需要为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”声明所有潜在的socket.io活动 变量
  2. socket.action =更新特定套接字
  3. sockets.action =更新所有套接字。
  4. 在名称中有io意味着套接字只有两个值,on 或者关闭因此将socket.on视为函数“触发”的类型。
  5. 了解app.js(服务器端数据)如何为各种'socket.on'条件定义不同的功能?这就是套接字连接到index.html ant与你的应用用户交谈的方式。 (客户端数据)
  6. HTH

相关问题