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
|
exports.UDPSocket = UDPSocket
// exports.TCPSocket = TCPSocket
var EventEmitter = require('events').EventEmitter
var string = require('./lib/string')
var util = require('util')
util.inherits(UDPSocket, EventEmitter)
function UDPSocket () {
var self = this
if (!(self instanceof UDPSocket)) return new UDPSocket()
EventEmitter.call(self)
self.sendBuffer = []
self.localPort = 0
self.bound = false
chrome.socket.create('udp', {}, function (createInfo) {
self.id = createInfo.socketId
chrome.socket.bind(self.id, '0.0.0.0', 0, function (result) {
if (result < 0) {
console.warn('UDPSocket ' + self.id + ' failed to bind')
return
}
chrome.socket.getInfo(self.id, function (result) {
if (!result.localPort) {
console.warn('Cannot get local port for UDPSocket ' + self.id)
return
}
self.localPort = result.localPort
self._onBound()
})
})
})
}
UDPSocket.prototype._onBound = function () {
var self = this
self.bound = true
self.emit('bound', self.localPort)
while (self.sendBuffer.length) {
var message = self.sendBuffer.shift()
self.sendTo(message.data, message.host, message.port, message.cb)
}
self._recvLoop()
}
UDPSocket.prototype.sendTo = function (data, host, port, cb) {
var self = this
cb = cb || function() {}
if (!self.bound) {
self.sendBuffer.push({'data': data, 'host': host, 'port': port, 'cb': cb});
return
}
if (typeof data === 'string') {
data = bops.from(data).buffer
} else if (data.buffer) {
data = data.buffer
}
chrome.socket.sendTo(self.id, data, host, port, function (writeInfo) {
if (writeInfo.bytesWritten < 0) {
console.warn('UDPSocket ' + self.id + ' write: ' + writeInfo.bytesWritten)
}
cb()
})
}
UDPSocket.prototype._recvLoop = function() {
var self = this
chrome.socket.recvFrom(self.id, function (recvFromInfo) {
if (recvFromInfo.resultCode > 0) {
self.emit('data', recvFromInfo.data, recvFromInfo.address,
recvFromInfo.port)
self._recvLoop()
} else {
console.warn('UDPSocket ' + self.id + ' recvFrom: ', recvFromInfo)
}
})
}
|