-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
tcp-network.js
75 lines (64 loc) · 1.81 KB
/
tcp-network.js
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
// SPDX-FileCopyrightText: 2023 the cable-client authors
//
// SPDX-License-Identifier: AGPL-3.0-or-later
const lpstream = require("length-prefixed-stream")
const b4a = require("b4a")
const net = require("net")
const debug = require("debug")("transport:tcp")
const EventEmitter = require("events").EventEmitter
class Network extends EventEmitter {
constructor(opts) {
super()
if (!opts) {
opts = {}
}
this.serve = opts.serve || false
this.port = opts.tcpPort || 13333
this.ip = opts.ip || "127.0.0.1"
this.peers = []
if (opts.serve) {
this._startServer()
} else {
const socket = net.connect(this.port, this.ip)
this._setupPeer(socket)
}
}
_startServer() {
const server = net.createServer(socket => {
this._setupPeer(socket)
})
server.listen(this.port)
}
_setupPeer(socket) {
const peer = {
id: (Math.random() + "").slice(10),
// encode: socket lpstream.encode(),
decode: lpstream.decode(),
socket
}
socket.pipe(peer.decode)
socket.on("data", (data) => { debug("raw socket data", data) })
socket.on("connection", (c) => { debug("connection", c) })
peer.decode.on("data", this._handleSocketData.bind(this))
this.peers.push(peer)
this.emit("peer-connected", socket)
socket.on("end", () => {
const index = this.peers.findIndex(p => p.id === peer.id)
this.peers.splice(index, 1)
debug("connection:end")
this.emit("peer-disconnected", socket)
})
}
_handleSocketData(msg) {
const data = b4a.from(msg.toString("hex"), "hex")
debug("LEN data", data)
this.emit("data", { address: "", data })
}
broadcast (data) {
debug("broadcast data", data)
this.peers.forEach(peer => {
peer.socket.write(data)
})
}
}
module.exports = { Network }