-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_tcp_node.js
63 lines (52 loc) · 1.68 KB
/
test_tcp_node.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
/*
* This work has been done by Phillip Ochola Makanyengo
* Email: [email protected]
*
* This work uses open source code and libraries and
* can therefore be replicated unless certain portions
* are stated otherwise.
*
* Please refer to the author when using the code.
*
*/
//Nodejs implementation of a tcp server
// Import required Modules
var comms = require('morphbridge').comms,
logger = require('morphbridge').logger,
channels_obj = require('morphbridge').channels_obj,
mainChannel = channels_obj.newChannel(),
net = require('net'),
HOST = '0.0.0.0',
PORT = 9501;
//Handle internode messages
/*
Place your own function to handle messages recieved by the node.
*/
var handle = function(msg){
//logger.logStat('TCP node Received ZMQ message');
mainChannel.tcp_bcast(msg);
};
//Socket Initialisation
comms.init(handle); //Pass message handling function to sub_socket
// Create a Server
net.createServer(function(sock) {
// Introductory Message
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
mainChannel.subscribe(sock);
// Add a 'data' event handler to this instance of socket
sock.on('data', function(data) {
if(comms.transmit(data))
console.log("Message Sent from: "+sock.remoteAddress);
});
// Add a 'close' event handler to this instance of socket
sock.on('close', function(data) {
console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
mainChannel.unsubscribe(sock);
});
}).listen(PORT, HOST);
console.log('Server listening on ' + HOST +':'+ PORT);
process.on('SIGINT', function() {
comms.close()
console.log('\nClosed')
process.exit();
});