-
Notifications
You must be signed in to change notification settings - Fork 374
/
handler.ts
73 lines (64 loc) · 1.61 KB
/
handler.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
63
64
65
66
67
68
69
70
71
72
import { Package , Protocol } from 'pinus-protocol';
import { getLogger } from 'pinus-logger';
import { ISocket } from '../../interfaces/ISocket';
let logger = getLogger('pinus', __filename);
let handlers : {[packageType : number] : (socket : ISocket , pkg : any)=>void} = {};
let ST_INITED = 0;
let ST_WAIT_ACK = 1;
let ST_WORKING = 2;
let ST_CLOSED = 3;
let handleHandshake = function (socket : ISocket , pkg : any)
{
if (socket.state !== ST_INITED)
{
return;
}
try
{
socket.emit('handshake', JSON.parse(Protocol.strdecode(pkg.body)));
} catch (ex)
{
socket.emit('handshake', {});
}
};
let handleHandshakeAck = function (socket : ISocket , pkg : any)
{
if (socket.state !== ST_WAIT_ACK)
{
return;
}
socket.state = ST_WORKING;
socket.emit('heartbeat');
};
let handleHeartbeat = function (socket : ISocket , pkg : any)
{
if (socket.state !== ST_WORKING)
{
return;
}
socket.emit('heartbeat');
};
let handleData = function (socket : ISocket , pkg : any)
{
if (socket.state !== ST_WORKING)
{
return;
}
socket.emit('message', pkg);
};
handlers[Package.TYPE_HANDSHAKE] = handleHandshake;
handlers[Package.TYPE_HANDSHAKE_ACK] = handleHandshakeAck;
handlers[Package.TYPE_HEARTBEAT] = handleHeartbeat;
handlers[Package.TYPE_DATA] = handleData;
export default function (socket : ISocket, pkg : any)
{
let handler = handlers[pkg.type];
if (!!handler)
{
handler(socket, pkg);
} else
{
logger.error('could not find handle invalid data package.');
socket.disconnect();
}
};