UNPKG

2.55 kBJavaScriptView Raw
1(function() {
2 var _, events, listen, net, open;
3
4 _ = require('lodash');
5
6 events = require('events');
7
8 net = require('net');
9
10 exports.create = function() {
11 var protocol;
12 protocol = new events.EventEmitter();
13 protocol.listen = function(config, defPort) {
14 return listen(protocol, config, defPort);
15 };
16 protocol.end = function() {};
17 return protocol;
18 };
19
20 listen = function(protocol, config, defPort) {
21 protocol.status = {};
22 protocol.config = config;
23 return open(protocol, defPort);
24 };
25
26 open = function(protocol, defPort) {
27 var ended, server;
28 _.defaults(protocol.config, {
29 listenPort: defPort || 3015
30 });
31 ended = false;
32 server = new net.Server();
33 server.on('error', function(err) {
34 return protocol.emit('error', err);
35 });
36 server.on('close', function() {
37 return protocol.emit('close');
38 });
39 server.on('listening', function() {
40 protocol.end = function() {
41 if (!ended) {
42 server.close();
43 }
44 return ended = true;
45 };
46 return protocol.emit('listening', server.address());
47 });
48 server.on('connection', function(socket) {
49 var draw, handle, readAccumulate, sp;
50 sp = new events.EventEmitter();
51 _.assign(sp, {
52 reply: function(data) {
53 return socket.write(JSON.stringify(data));
54 },
55 end: function(data) {
56 if (data != null) {
57 return socket.end(JSON.stringify(data));
58 } else {
59 return socket.end();
60 }
61 }
62 });
63 protocol.emit('connection', sp);
64 socket.setEncoding('utf8');
65 socket.on('error', function(err) {
66 return sp.emit('error', err);
67 });
68 socket.on('close', function(hadErr) {
69 return sp.emit('close', hadErr);
70 });
71 socket.on('data', function(data) {
72 sp.emit('data', data);
73 return draw(data);
74 });
75 readAccumulate = '';
76 draw = function(sdata) {
77 var etx, rdata, results;
78 readAccumulate += sdata;
79 results = [];
80 while ((etx = readAccumulate.indexOf('\x03')) !== -1) {
81 rdata = readAccumulate.substr(0, etx);
82 readAccumulate = readAccumulate.substr(etx + 1);
83 results.push(handle(rdata));
84 }
85 return results;
86 };
87 return handle = function(sdata) {
88 return protocol.emit('command', sdata.trim(), sp);
89 };
90 });
91 return server.listen({
92 port: protocol.config.listenPort
93 });
94 };
95
96}).call(this);