用於處理使用者的示例伺服器端程式碼

首先,需要注意的是,當建立一個新套接字時,會為其分配一個唯一的 Id,通過呼叫 socket.id 來檢索它。然後可以將此 id 儲存在 user 物件中,並且我們可以分配諸如使用者名稱之類的識別符號,該使用者名稱已在本示例中用於檢索 user 物件。

/**
 * Created by Liam Read on 27/04/2017.
 */

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);

function User(socketId) {

    this.id = socketId;
    this.status = "online";
    this.username = "bob";

    this.getId = function () {
        return this.id;
    };

    this.getName = function () {
        return this.username;
    };

    this.getStatus = function () {
        return this.status;
    };

    this.setStatus = function (newStatus) {
        this.status = newStatus;
    }
}

var userMap = new Map();

/**
 * Once a connection has been opened this will be called.
 */
io.on('connection', function (socket) {

    var user;

    /**
     * When a user has entered there username and password we create a new entry within the userMap.
     */
    socket.on('registerUser', function (data) {

        userMap.set(data.name, new User(socket.id));

        //Lets make the user object available to all other methods to make our code DRY.
        user = userMap.get(data.name);
    });

    socket.on('loginUser', function (data) {
        if (userMap.has(data.name)) {
            //user has been found

            user = userMap.get(data.name);
        } else {
            //Let the client know that no account was found when attempting to sign in.
            socket.emit('noAccountFound', {
                msg: "No account was found"
            });
        }
    });

    socket.on('disconnect', function () {
        //Let's set this users status to offline.
        user.setStatus("offline");
    });

    /**
     * Dummy server event that represents a client looking to send a message to another user.
     */
    socket.on('sendAnotherUserAMessage', function (data) {

        //Make note here that by checking to see if the user exists within the map we can be sure that when
        // retrieving the value after && that we won't have any unexpected errors.
        if (userMap.has(data.name) && userMap.get(data.name).getStatus() !== "offline") {
            var OtherUser = userMap.get(data.name);
        } else {
            //We use a return here so further code isn't executed, you could replace this with some for of
            //error handling or a different event back to the user.
            return;
        }

        //Lets send our message to the user.
        io.to(OtherUser.getId()).emit('recMessage', {
            msg: "Nice code!"
        })
});

});

這絕不是一個儘可能接近可能的完整例子,但應該對處理 users 的方法有基本的瞭解。