-
Notifications
You must be signed in to change notification settings - Fork 381
/
siosocket.ts
98 lines (83 loc) · 1.88 KB
/
siosocket.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import * as util from 'util';
import { EventEmitter } from 'events';
import { ISocket } from '../interfaces/ISocket';
let ST_INITED = 0;
let ST_CLOSED = 1;
/**
* Socket class that wraps socket.io socket to provide unified interface for up level.
*/
export class SioSocket extends EventEmitter implements ISocket
{
id: number;
socket: SocketIO.Socket;
remoteAddress: { ip: string };
state: number;
constructor(id: number, socket: SocketIO.Socket)
{
super();
this.id = id;
this.socket = socket;
this.remoteAddress = {
ip: socket.handshake.address
};
let self = this;
socket.on('disconnect', this.emit.bind(this, 'disconnect'));
socket.on('error', this.emit.bind(this, 'error'));
socket.on('message', function (msg)
{
self.emit('message', msg);
});
this.state = ST_INITED;
// TODO: any other events?
};
send(msg: any)
{
if (this.state !== ST_INITED)
{
return;
}
if (typeof msg !== 'string')
{
msg = JSON.stringify(msg);
}
this.socket.send(msg);
};
sendRaw = this.send;
disconnect()
{
if (this.state === ST_CLOSED)
{
return;
}
this.state = ST_CLOSED;
this.socket.disconnect();
};
sendBatch(msgs: any[])
{
this.send(encodeBatch(msgs));
};
}
/**
* Encode batch msg to client
*/
let encodeBatch = function (msgs: any[])
{
let res = '[', msg;
for (let i = 0, l = msgs.length; i < l; i++)
{
if (i > 0)
{
res += ',';
}
msg = msgs[i];
if (typeof msg === 'string')
{
res += msg;
} else
{
res += JSON.stringify(msg);
}
}
res += ']';
return res;
};