所以我才刚刚开始学习/使用套接字。
我的想法是使类脱离套接字,因为(至少对我而言)通过该类的实例来管理类更加容易。
我的示例代码:
const io = require('socket.io')();
const redis = require('socket.io-redis');
const util = require('util');
const adapter = redis({ host: 'localhost', port: 6379 });
io.adapter(adapter);
const ioa = io.of('/').adapter;
ioa.clients = util.promisify(ioa.clients);
ioa.clientRooms = util.promisify(ioa.clientRooms);
ioa.remoteJoin = util.promisify(ioa.remoteJoin);
ioa.remoteLeave = util.promisify(ioa.remoteLeave);
ioa.customRequest = util.promisify(ioa.customRequest);
io.on('connect', (socket) => {
const s = new Socket(socket)
})
class Socket {
constructor(socket) {
this.socket = socket;
this.id = socket.id;
this.user = null;
this.connected();
this.listen();
}
listen() {
this.socket.on('send message', (data) => this.sendMessage(data));
this.socket.on('disconnect', () => this.disconnect());
this.socket.on('authenticate', (data) => this.authenticate(data));
this.socket.on('join room', (data) => this.joinRoom(data));
this.socket.on('get my rooms', () => this.getMyRooms());
}
async connected() {
const clients = await ioa.clients();
io.emit('currentUsersCount', clients.length);
io.emit('connectedUsers', clients);
}
authenticate(data) {
}
sendMessage(data) {
const message = {
sender: this.id,
message: data.message
};
this.socket.broadcast.emit('send message', message)
}
async getMyRooms() {
const rooms = await ioa.clientRooms(this.id);
this.socket.emit('get my rooms', rooms)
}
async joinRoom({ id }) {
await ioa.remoteJoin(this.id, id);
this.socket.emit('console', `You have joined room: ${id}`)
this.socket.to(id).emit('console', `${this.id} has joined ${id}`)
}
async leaveRoom(id) {
}
async disconnect() {
const clients = await ioa.clients();
io.emit('currentUsersCount', clients.length);
io.emit('connectedUsers', clients)
}
}
module.exports = io;
我还需要redis适配器,因为该应用程序将处于群集模式。
我还有一个authenticate方法,在这里我将对用户进行身份验证,并将用户对象(将存储在mongo中)放在socket.class中的this.user变量中。
现在我的问题是,由于我拥有Socket类的所有这些实例,并且一个用户需要向另一个用户发送消息,因此我需要找到一个与该用户匹配的套接字。我该怎么做?