This repository was archived by the owner on Sep 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathudpsocket.js
More file actions
98 lines (85 loc) · 2.12 KB
/
Copy pathudpsocket.js
File metadata and controls
98 lines (85 loc) · 2.12 KB
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
var util = require('util');
var handler = require('./common/handler');
var protocol = require('pomelo-protocol');
var Package = protocol.Package;
var EventEmitter = require('events').EventEmitter;
var logger = require('pomelo-logger').getLogger('pomelo', __filename);
var ST_INITED = 0;
var ST_WAIT_ACK = 1;
var ST_WORKING = 2;
var ST_CLOSED = 3;
var Socket = function(id, socket, peer) {
EventEmitter.call(this);
this.id = id;
this.socket = socket;
this.peer = peer;
this.remoteAddress = {
ip: this.peer.address,
port: this.peer.port
};
var self = this;
this.on('package', function(pkg) {
if(!!pkg) {
pkg = Package.decode(pkg);
handler(self, pkg);
}
});
this.state = ST_INITED;
};
util.inherits(Socket, EventEmitter);
module.exports = Socket;
/**
* Send byte data package to client.
*
* @param {Buffer} msg byte data
*/
Socket.prototype.send = function(msg) {
if(this.state !== ST_WORKING) {
return;
}
if(msg instanceof String) {
msg = new Buffer(msg);
} else if(!(msg instanceof Buffer)) {
msg = new Buffer(JSON.stringify(msg));
}
this.sendRaw(Package.encode(Package.TYPE_DATA, msg));
};
Socket.prototype.sendRaw = function(msg) {
this.socket.send(msg, 0, msg.length, this.remoteAddress.port, this.remoteAddress.ip, function(err, bytes) {
if(!!err) {
logger.error('send msg to remote with err: %j', err.stack);
return;
}
});
};
Socket.prototype.sendForce = function(msg) {
if(this.state === ST_CLOSED) {
return;
}
this.sendRaw(msg);
};
Socket.prototype.handshakeResponse = function(resp) {
if(this.state !== ST_INITED) {
return;
}
this.sendRaw(resp);
this.state = ST_WAIT_ACK;
};
Socket.prototype.sendBatch = function(msgs) {
if(this.state !== ST_WORKING) {
return;
}
var rs = [];
for(var i=0; i<msgs.length; i++) {
var src = Package.encode(Package.TYPE_DATA, msgs[i]);
rs.push(src);
}
this.sendRaw(Buffer.concat(rs));
};
Socket.prototype.disconnect = function() {
if(this.state === ST_CLOSED) {
return;
}
this.state = ST_CLOSED;
this.emit('disconnect', 'the connection is disconnected.');
};