/
PacketChannelInvoker.ts
62 lines (53 loc) · 2.13 KB
/
PacketChannelInvoker.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { RawData } from 'ws';
import { BitStream } from 'ts-bitstream';
import { Pipe } from '../../pipe/Pipe';
import { ConnectionID } from '../../connection/ConnectionID';
import { ProtocolMode } from '../../sock/ProtocolMode';
export class PacketChannelInvoker {
private pipe : Pipe;
constructor(pipe : Pipe){
this.pipe = pipe;
}
/**
* Читает канал и выполняет пакеты
* @param data данные канала
* @returns читает канал
*/
public readData(data : RawData, id? : ConnectionID) {
try{
let bs : BitStream = new BitStream(data.toString());
let packetId = bs.readInt();
if(isNaN(packetId)){
/**
* Если данные не верные, или повреждены - отключаем такого чудика
*/
console.debug(`Malformed packet recived from ${id ? id : "server"}`);
if(this.pipe.getPhantom().getProtocolMode() === ProtocolMode.SERVER && id){
let sock = this.pipe.getConnectionManager().getSocketByID(id);
sock.close(0, `Incorrect protocol data, socket closed by peer`);
this.pipe.getConnectionManager().removeConnectionByID(id);
}
return;
}
let packet = this.pipe.getPhantom().getPacketManager().getById(packetId);
if(!packet){
console.debug(`Bad packet id ${packetId}`);
return;
}
packet.packet.setBinnaryData(data);
if(id){
packet.packet.setSender(id);
}else{
packet.packet.setSender("SERVER");
}
if(packet.context){
packet.func.call(packet.context, packet.packet.recive(bs));
}else{
packet.func(packet.packet.recive(bs));
}
}catch(e){
console.debug(`Malformed packet recived`);
console.debug(e);
}
}
}