Skip to content

Commit 1798889

Browse files
committed
feat: SocketApplication
1 parent e898b91 commit 1798889

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

src/apps/socket.js

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
'use strict';
2+
3+
const net = require('net');
4+
const EventEmitter = require('events');
5+
const Application = require('./app');
6+
const { debug, printer } = require('@axiosleo/cli-tool');
7+
8+
class SocketApplication extends Application {
9+
constructor(config = {}) {
10+
super(config);
11+
this.event = new EventEmitter();
12+
this.port = this.config.port || 8081;
13+
this.connections = {};
14+
}
15+
16+
async start() {
17+
const server = net.createServer((connection) => {
18+
this.event.emit('connection', connection);
19+
connection.pipe(connection);
20+
connection.on('data', function (data) {
21+
try {
22+
debug.dump(Buffer.from(data).toString());
23+
// const context = JSON.parse(data.toString());
24+
// if (context.action === 'server.connect' && context.code) {
25+
// conn.id = context.code;
26+
// this.connections[conn.id] = conn;
27+
// } else {
28+
// this.dispatch(context, conn);
29+
// }
30+
} catch (err) {
31+
debug.log(err);
32+
}
33+
});
34+
});
35+
server.listen(this.port, () => {
36+
printer.info(`Server is running on port ${this.port}`);
37+
this.event.emit('listen', this.port);
38+
});
39+
}
40+
41+
async dispatch(context, conn) {
42+
const connections = this.connections;
43+
const action = context.action;
44+
switch (action) {
45+
case 'broadcast': {
46+
const conns = Object.keys(connections);
47+
// debug.log('connections:', conns.length);
48+
if (conns.length) {
49+
conns.map(id => connections[id].connection.write(JSON.stringify(context.data)));
50+
}
51+
break;
52+
}
53+
default: {
54+
debug.log(context);
55+
}
56+
}
57+
}
58+
}
59+
60+
module.exports = SocketApplication;

0 commit comments

Comments
 (0)