feat: optimize websocket

Signed-off-by: MiaoWoo <admin@yumc.pw>
This commit is contained in:
2020-11-13 09:40:47 +08:00
parent d769a9c8ca
commit 7f5929bc87
10 changed files with 195 additions and 126 deletions

View File

@ -21,7 +21,7 @@ interface WebSocketServer extends EventEmitter {
class Server implements SocketIO.Server {
private websocketServer: WebSocketServer
private allClients: { [key: string]: Client }
private allClients: Map<string, Client>
engine: { ws: any }
nsps: { [namespace: string]: Namespace }
@ -35,7 +35,7 @@ class Server implements SocketIO.Server {
constructor(instance: any, options: ServerOptions) {
if (!instance) { throw new Error('instance can\'t be undefiend!') }
this.allClients = {}
this.allClients = new Map()
this.nsps = {}
this.sockets = new Namespace('/', this)
this.nsps['/'] = this.sockets
@ -99,18 +99,17 @@ class Server implements SocketIO.Server {
bind(srv: any): SocketIO.Server {
throw new Error("Method not implemented.")
}
onconnection(socket: Client): SocketIO.Server {
this.allClients[socket.id] = socket
socket.packet({
onconnection(client: Client): SocketIO.Server {
client.packet({
type: PacketTypes.OPEN,
data: {
sid: socket.id,
sid: client.id,
upgrades: [],
pingInterval: 25000,
pingTimeout: 5000
}
})
this.sockets.add(socket)
this.sockets.add(client)
return this
}
of(nsp: string): Namespace {
@ -164,20 +163,35 @@ class Server implements SocketIO.Server {
private initServer() {
this.websocketServer.on(ServerEvent.connect, (socket: SocketIO.EngineSocket) => {
let client = new Client(this, socket)
this.allClients.set(socket.id, client)
this.onconnection(client)
})
this.websocketServer.on(ServerEvent.message, (socket: SocketIO.EngineSocket, text) => {
this.processPacket(this.parser.decode(text), this.allClients[socket.id])
if (this.allClients.has(socket.id)) {
this.processPacket(this.parser.decode(text), this.allClients.get(socket.id))
} else {
console.error(`unknow engine socket ${socket.id} reciver message ${text}`)
}
})
this.websocketServer.on(ServerEvent.disconnect, (socket: SocketIO.EngineSocket, reason) => {
this.allClients[socket.id].onclose(reason)
delete this.allClients[socket.id]
if (this.allClients.has(socket.id)) {
this.allClients.get(socket.id).onclose(reason)
this.allClients.delete(socket.id)
} else {
console.error(`unknow engine socket ${socket?.id} disconnect cause ${reason}`)
}
})
this.websocketServer.on(ServerEvent.error, (socket: SocketIO.EngineSocket, cause) => {
if (socket.listeners(ServerEvent.error).length) {
socket.emit(ServerEvent.error, cause)
if (this.allClients.has(socket?.id)) {
if (socket.listeners(ServerEvent.error).length) {
socket.emit(ServerEvent.error, cause)
} else {
console.error(`engine socket ${socket.id} cause error: ${cause}`)
console.ex(cause)
}
} else {
console.error(`client ${socket.id} cause error: ${cause}`)
console.error(`unknow engine socket ${socket?.id} cause error: ${cause}`)
console.ex(cause)
}
})
}
@ -219,5 +233,6 @@ export {
Server,
Socket,
Client,
Namespace,
ServerOptions
}

View File

@ -1,40 +1,40 @@
import { EventEmitter } from 'events'
import { Client } from './client'
import { SocketIO } from './interfaces';
import { ServerEvent } from './constants';
import { Socket } from './socket';
import { Adapter } from './adapter';
import { SocketIO } from './interfaces'
import { ServerEvent } from './constants'
import { Socket } from './socket'
import { Adapter } from './adapter'
import { Server } from './index'
import { Packet } from './packet';
import { PacketTypes, SubPacketTypes } from './types';
import { Packet } from './packet'
import { PacketTypes, SubPacketTypes } from './types'
export class Namespace extends EventEmitter implements SocketIO.Namespace {
name: string;
server: Server;
sockets: { [id: string]: Socket; };
connected: { [id: string]: Socket; };
adapter: SocketIO.Adapter;
json: SocketIO.Namespace;
name: string
server: Server
sockets: { [id: string]: Socket }
connected: { [id: string]: Socket }
adapter: SocketIO.Adapter
json: SocketIO.Namespace
fns: any[];
ids: number;
rooms: string[];
flags: { [key: string]: boolean };
fns: any[]
ids: number
rooms: string[]
flags: { [key: string]: boolean }
private events = ['connect', 'connection', 'newListener']
constructor(name: string, server: Server) {
super();
this.name = name;
this.server = server;
this.sockets = {};
this.connected = {};
this.fns = [];
this.ids = 0;
this.rooms = [];
this.flags = {};
this.adapter = new Adapter(this);
super()
this.name = name
this.server = server
this.sockets = {}
this.connected = {}
this.fns = []
this.ids = 0
this.rooms = []
this.flags = {}
this.adapter = new Adapter(this)
}
initAdapter() {
// @ts-ignore
@ -42,39 +42,39 @@ export class Namespace extends EventEmitter implements SocketIO.Namespace {
}
add(client: Client, query?: any, callback?: () => void) {
// client.conn.request.url();
let socket = new Socket(this, client, {});
this.sockets[client.id] = socket;
client.nsps[this.name] = socket;
this.onconnection(socket);
return socket;
let socket = new Socket(this, client, {})
this.sockets[client.id] = socket
client.nsps[this.name] = socket
this.onconnection(socket)
return socket
}
del(client: Client) {
let socket = this.sockets[client.id];
socket.disconnect();
delete this.sockets[client.id];
let socket = this.sockets[client.id]
socket.disconnect()
delete this.sockets[client.id]
}
use(fn: (socket: SocketIO.Socket, fn: (err?: any) => void) => void): SocketIO.Namespace {
throw new Error("Method not implemented.");
throw new Error("Method not implemented.")
}
to(room: string): SocketIO.Namespace {
if (!~this.rooms.indexOf(room)) this.rooms.push(room);
return this;
if (!~this.rooms.indexOf(room)) this.rooms.push(room)
return this
}
in(room: string): SocketIO.Namespace {
return this.to(room);
return this.to(room)
}
send(...args: any[]): SocketIO.Namespace {
super.emit('message', ...args)
return this;
return this
}
write(...args: any[]): SocketIO.Namespace {
return this.send(...args);
return this.send(...args)
}
emit(event: string, ...args: any[]): boolean {
if (~this.events.indexOf(event)) {
super.emit(event, ...args);
super.emit(event, ...args)
// @ts-ignore
return this;
return this
}
// set up packet object
var packet = {
@ -85,54 +85,58 @@ export class Namespace extends EventEmitter implements SocketIO.Namespace {
}
if ('function' == typeof args[args.length - 1]) {
throw new Error('Callbacks are not supported when broadcasting');
throw new Error('Callbacks are not supported when broadcasting')
}
var rooms = this.rooms.slice(0);
var flags = Object.assign({}, this.flags);
var rooms = this.rooms.slice(0)
var flags = Object.assign({}, this.flags)
// reset flags
this.rooms = [];
this.flags = {};
this.rooms = []
this.flags = {}
this.adapter.broadcast(packet, {
rooms: rooms,
flags: flags
});
})
// @ts-ignore
return this;
return this
}
hasBin(args: any[]) {
return false;
return false
}
clients(fn: Function): SocketIO.Namespace {
clients(fn: (sockets: Socket[]) => SocketIO.Namespace): SocketIO.Namespace {
return fn(Object.values(this.sockets))
}
compress(compress: boolean): SocketIO.Namespace {
throw new Error("Method not implemented.");
throw new Error("Method not implemented.")
}
process(packet: Packet, client: Client) {
switch (packet.sub_type) {
case SubPacketTypes.CONNECT:
this.add(client);
break;
this.add(client)
break
default:
this.sockets[client.id].onpacket(packet);
break;
this.sockets[client.id].onpacket(packet)
break
}
}
remove(socket: Socket) {
if (this.sockets.hasOwnProperty(socket.id)) {
delete this.sockets[socket.id];
delete this.sockets[socket.id]
} else {
// debug('ignoring remove for %s', socket.id);
}
}
close() {
this.removeAllListeners('connect')
Object.values(this.sockets).forEach(socket => socket.disconnect(false))
}
private onconnection(socket: any) {
let client = socket as Socket;
this.sockets[client.id] = client;
let client = socket as Socket
this.sockets[client.id] = client
this.emit(ServerEvent.connect, socket)
client.onconnect()
this.emit(ServerEvent.connect, socket);
this.emit(ServerEvent.connection, socket);
this.emit(ServerEvent.connection, socket)
}
}