-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
89 lines (79 loc) · 2.81 KB
/
app.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
let express = require('express');
let app = express();
let http = require('http').createServer(app);
let io = require('socket.io')(http);
let path = require('path');
let ss = require('socket.io-stream');
let fs = require('fs');
let lineReader = require('line-reader');
app.use(express.static('public'))
app.get('/*', function(req, res){
res.sendFile(__dirname + '/index.html');
});
//stores client socket address
let cleintsMap = {};
let routingTable = {};
io.on('connection', function(socket){
console.log('New Connection!!');
//handeling fileUpload
ss(socket).on('sendFile', function(stream, data) {
console.log("Recieved file ", data.name, " from ", data.from, " to send at node ", data.to);
var filename = path.basename(data.name);
stream.pipe(fs.createWriteStream(filename))
.on('finish', function() {
//sendFile to destination node line by line
lineReader.eachLine(data.name, function(line, last) {
console.log(line, "\n");
let message = {message: line, from: data.from}
if(cleintsMap[data.to] == undefined) {
console.log("Destination node ", to ," not found");
}
else {
cleintsMap[data.to].socket.emit('messageFromServer', message);
if(last) {
console.log("File send to destination node successfully!");
}
}
});
});
});
//handle client echo message
socket.on("helloFromClient", function(nodeName, nodeDistance) {
cleintsMap[nodeName] = {socket: socket, distance: nodeDistance};
console.log("NewNode: ", nodeName, " at Distance: ", nodeDistance);
routingTable[nodeName] = {node: nodeName, distance: nodeDistance};
console.log("Routing Table\n", routingTable);
});
//handle sendMessage event
socket.on("sendMessage", function(message, from, to) {
console.log("NewMessage ", message, " from ", from, " to ", to);
//send message to destination node
let data = {message: message, from: from};
if(to == "S") {
console.log("Message for server!");
}
else if(cleintsMap[to] == undefined) {
console.log("Destination node ", to ," not found");
}
else {
console.log("Message forwarded by server to ", to);
cleintsMap[to].socket.emit("messageFromServer", data);
}
});
//handle node disconnect
socket.on('disconnect', function() {
console.log('Disconnected form server!');
Object.keys(cleintsMap).forEach(key => {
if(cleintsMap[key].socket == socket) {
//delete node entry from clientsMap & routingTable
delete cleintsMap[key];
delete routingTable[key];
console.log("Deleting Node ", key);
console.log("Updated Routing Table\n", routingTable);
}
});
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});