-
Notifications
You must be signed in to change notification settings - Fork 383
/
udpsocket.ts
128 lines (116 loc) · 2.85 KB
/
udpsocket.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import * as util from 'util';
import { default as handler } from './common/handler';
import { Package } from 'pinus-protocol';
import * as EventEmitter from 'events';
import { getLogger } from 'pinus-logger';
import { ISocket } from '../interfaces/ISocket';
import * as dgram from "dgram";
let logger = getLogger('pinus', __filename);
let ST_INITED = 0;
let ST_WAIT_ACK = 1;
let ST_WORKING = 2;
let ST_CLOSED = 3;
export class UdpSocket extends EventEmitter implements ISocket
{
id: number;
socket: dgram.Socket;
peer: dgram.RemoteInfo;
host: string;
port: number;
remoteAddress: { ip: string; port: number };
state: number;
constructor(id : number, socket: dgram.Socket, peer : dgram.RemoteInfo)
{
super();
this.id = id;
this.socket = socket;
this.peer = peer;
this.host = peer.address;
this.port = peer.port;
this.remoteAddress = {
ip: this.host,
port: this.port
};
let self = this;
this.on('package', function (pkg)
{
if (!!pkg)
{
pkg = Package.decode(pkg);
handler(self, pkg);
}
});
this.state = ST_INITED;
};
/**
* Send byte data package to client.
*
* @param {Buffer} msg byte data
*/
send(msg: any)
{
if (this.state !== ST_WORKING)
{
return;
}
if (msg instanceof String)
{
msg = new Buffer(msg as string);
} else if (!(msg instanceof Buffer))
{
msg = new Buffer(JSON.stringify(msg));
}
this.sendRaw(Package.encode(Package.TYPE_DATA, msg));
};
sendRaw(msg : any)
{
this.socket.send(msg, 0, msg.length, this.port, this.host, function (err, bytes)
{
if (!!err)
{
logger.error('send msg to remote with err: %j', err.stack);
return;
}
});
};
sendForce(msg : any)
{
if (this.state === ST_CLOSED)
{
return;
}
this.sendRaw(msg);
};
handshakeResponse(resp : any)
{
if (this.state !== ST_INITED)
{
return;
}
this.sendRaw(resp);
this.state = ST_WAIT_ACK;
};
sendBatch(msgs : any[])
{
if (this.state !== ST_WORKING)
{
return;
}
let rs = [];
for (let i = 0; i < msgs.length; i++)
{
let src = Package.encode(Package.TYPE_DATA, msgs[i]);
rs.push(src);
}
this.sendRaw(Buffer.concat(rs));
};
disconnect()
{
if (this.state === ST_CLOSED)
{
return;
}
this.state = ST_CLOSED;
this.emit('disconnect', 'the connection is disconnected.');
};
}