Node.js socket.io+;的最佳方法是什么;快速会话支持?

Node.js socket.io+;的最佳方法是什么;快速会话支持?,node.js,session,express,socket.io,Node.js,Session,Express,Socket.io,我是node.js新手,我似乎找不到一个好方法来创建一个会话,该会话可以由来自express和socket.io的用户进行交互。我已经尝试了很多解决方案,但是没有一个有效。如有任何建议,将不胜感激 谢谢 可以给我您正在使用的确切代码片段吗?我能够从示例中获得一个基本的聊天应用程序和多人游戏,并从节点中运行,我将查看您尝试使用的示例 简而言之,您需要为io建立一个变量来要求sockets.io模块。从那里,您还需要在app.js文件中写入所有可能发送和接收的套接字消息。这是我从你那里拿的 安装No

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


谢谢

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

简而言之,您需要为io建立一个变量来要求sockets.io模块。从那里,您还需要在app.js文件中写入所有可能发送和接收的套接字消息。这是我从你那里拿的

安装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"
 }
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');
    });
});
}

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

{
 "name": "mukhin_chat",
 "description": "example chat application with socket.io",
 "version": "0.0.1",
 "dependencies": {
    "express": "2.4.6",
    "socket.io": "0.8.4"
 }
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>

var socket=io.connect('http://localhost:8080');
//在连接到服务器时,通过匿名回调请求用户名
socket.on('connect',function(){
//调用服务器端函数“adduser”并发送一个参数(prompt的值)
emit('adduser',prompt(“你叫什么名字?”);
});
//侦听器,无论何时服务器发出“updatechat”,都会更新聊天主体
socket.on('updatechat',函数(用户名、数据){
$(“#对话”).append(“+username+”:“+data+”
”); }); //侦听器,每当服务器发出“updateusers”时,就会更新用户名列表 socket.on('updateusers',函数(数据){ $('#users').empty(); $。每个(数据、函数(键、值){ $(“#用户”).append(“”+key+“”); }); }); //加载页面 $(函数(){ //当客户端单击SEND时 $('#datasend')。单击(函数(){ var message=$('#data').val(); $('数据').val(''); //告诉服务器执行“sendchat”并发送一个参数 发出('sendchat',消息); }); //当客户端在键盘上按ENTER键时 $(“#数据”)。按键(功能(e){ 如果(e.which==13){ $(this.blur(); $('#datasend')。焦点()。单击(); } }); }); 使用者
使用:node app.js运行服务器本身

在命令提示窗口中

主要收获:

  • 用全局“io”声明所有潜在的sockets.io活动 变数
  • socket.action=更新特定套接字
  • sockets.action=更新所有套接字
  • 它的名称中有io,这意味着套接字将只有两个值,on 或off,因此将socket.on视为函数的“触发器”类型
  • 查看app.js(服务器端数据)如何为各种“socket.on”条件定义不同的函数?这就是套接字连接到index.html ant并与应用程序用户对话的方式。(客户端数据)

  • HTH

    谢谢分享您的代码。建议您更新expressJS 4.x的代码,因为您使用的是“express”:“2.4.6”版本太旧了。请使用never版本。从那时起,许多事情都发生了变化。最好是用Express 4.9编写谢谢。我们一定要澄清这一点:不是我的代码,michael的:)