用于处理用户的示例服务器端代码
首先,需要注意的是,当创建一个新套接字时,会为其分配一个唯一的 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
的方法有基本的了解。