Callback a function after a process - javascript

I use the bittorent-tracker package for get numbers of seeders and leechers for a given torrent but there is no way to know if the torrent scraping procedure is terminated client.on('scrape_terminated') for exemple ... Is there a way to detects the scraping is terminated ?
var Tracker = require('bittorrent-tracker')
var magnet = require('magnet-uri')
var magnetURI = "magnet:?xt=urn:btih:7a0e02e22744ddb807480f580cc328925d5810d4&dn=Terminator+2%3A+Judgment+Day+DC+%281991%29+1080p+BrRip+x264+-+YIFY&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Fzer0day.ch%3A1337&tr=udp%3A%2F%2Fopen.demonii.com%3A1337&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Fexodus.desync.com%3A6969"
var parsedTorrent = magnet(magnetURI)
var opts = {
infoHash: parsedTorrent.infoHash,
announce: parsedTorrent.announce,
peerId: new Buffer('01234567890123456789'), // hex string or Buffer
port: 6881 // torrent client port
}
var client = new Tracker(opts)
client.scrape();
client.on('scrape', function (data) {
console.log('number of seeders in the swarm: ' + data.complete)
console.log('number of leechers in the swarm: ' + data.incomplete)
});
client.on('error',function(data) {
console.log('erreur');
})

Related

Cannot connect or emit to Amazon ECS Socket.io Server via Socket.io from a HTML file located in S3 bucket

I am having trouble connecting and emitting to an ECS Fargate Socket.io Server on AWS via Socket.io from a HTML file located in a S3 bucket in the same AWS region.
The ECS Fargate Server's code is as follows:
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var AWS = require ('aws-sdk');
io.on('connect', function (socket){
console.log('connection made');
socket.on('disconnect', function (socketds) {
console.log("***********************************************");
console.log("Disconnected");
});
socket.on('reconnect', function (socketds) {
console.log("***********************************************");
console.log("Reconnected");
});
socket.on('c_status', function () {
console.log("*********************************************");
console.log("cstatus");
});
socket.on('app_message', function (mdata) {
console.log("***********************************************");
console.log("App-message:",mdata);
socket.emit('command1',mdata);
});
});
http.listen(3000, function () {
console.log('listening on *:3000');
});
And the relevant code of the HTML file is as follows:
<script>
const serverLocation = "http://application-load-balancer-dns-link:3000";
const socket = io(serverLocation);
function sendmsg() {
var date = new Date();
date.setHours(date.getHours() + 4);
var datetm = date.toISOString().split('.')[0]+"Z";
var node_id = $('#innode').val();
var clid = "0";
var msg = $('#message').val();
if (node_id.length === 1) {
var unitcode = "0" + "0" + node_id;
}
else if (node_id.length === 2) {
var unitcode = "0" + node_id;
}
else {
var unitcode = node_id;
}
var mdata = datetm+unitcode+msg;
socket.emit('app_message',mdata);
}
</script>
I have been at it for 2 days now and have not been able to figure it out. It just doesn't connect.
Any help is greatly appreciated.
If you need more information, please let me know.
1) Try checking the inbound rules of the security group associated with that instance.
2) Outbound rules should also be configured as its bidirectional (By Default allows all)
3) If they are perfect. Check whether timeout occurs or any other exception.

TypeError: serialport.parsers.readline is not a function

I am trying to run this program in Raspberry Pi 3.
I have installed nodejs and ws on my raspberry pi.
Then I installed serial port module.
I am trying to create this project:enter link description here
I have tried to find solutions everywhere but I could not find one.
If any one knows how to solve this problem please help me.
var webSocketUrl = "wss://api.artik.cloud/v1.1/websocket?ack=true";
var device_id = "5bb3ba9304674086bee67fa507a215cf"; //DEVICE ID
var device_token = "36b278345b6d4d11abf764ae213c5c70"; //DEVICE TOKEN
var WebSocket = require('ws');
var isWebSocketReady = false;
var data="";
var ws = null;
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
var sp = new SerialPort("/dev/ttyACM0", { //for serial communication with arduino
baudrate: 9600,
// The baud rate of uno is 9600
parser: serialport.parsers.readline("\n")
});
/**
* Gets the current time in millis
*/
function getTimeMillis(){
return parseInt(Date.now().toString());
}
/**
* Create a /websocket connection and setup GPIO pin
*/
function start() {
//Create the WebSocket connection
isWebSocketReady = false;
ws = new WebSocket(webSocketUrl);
ws.on('open', function() {
console.log("WebSocket connection is open ....");
register();
});
ws.on('message', function(data) {
//this loop is called whenever the client sends some message
handleRcvMsg(data); //data is send to the function handleRcvMsg()
});
ws.on('close', function() {
console.log("WebSocket connection is closed ....");
});
}
/**
* Sends a register message to /websocket endpoint
*/
//Client will only work when device gets registered from here
function register(){
console.log("Registering device on the WebSocket connection");
try{
var registerMessage = '{"type":"register", "sdid":"'+device_id+'", "Authorization":"bearer '+device_token+'", "cid":"'+getTimeMillis()+'"}';
console.log('Sending register message ' + registerMessage + '\n');
ws.send(registerMessage, {mask: true});
isWebSocketReady = true;
}
catch (e) {
console.error('Failed to register messages. Error in registering message: ' + e.toString());
}
}
//data after receiving is sent here for processing
function handleRcvMsg(msg){
var msgObj = JSON.parse(msg);
if (msgObj.type != "action") return; //Early return;
var actions = msgObj.data.actions;
var actionName = actions[0].name; //assume that there is only one action in actions
console.log("The received action is " + actionName);
}
/**
* Send one message to ARTIK Cloud
*/
//This function is responsible for sending commands to cloud
//function sendStateToArtikCloud(parking,temperature,water){
function sendDataToArtikCloud(pantry){
var result=pantry.split(" ");//data gets split by " " to get the values
try{
ts = ', "ts": '+getTimeMillis();
var data = {
"Garlic": result[1],
"Potato":result[2],
"Temperature":result[3],
"Chilli":result[4],
"Humidity": result[5],
"Ginger":result[6],
"Onion": result[7]
};
var payload = '{"sdid":"'+device_id+'"'+ts+', "data": '+JSON.stringify(data)+', "cid":"'+getTimeMillis()+'"}';
console.log('Sending payload ' + payload + '\n');
ws.send(payload, {mask: true});
} catch (e) {
console.error('Error in sending a message: ' + e.toString() +'\n');
}
}
function exitClosePins() {
console.log('Exit and destroy all pins!');
process.exit();
}
start();
//exectes every second when data is received from arduino (5sec programmed delay from arduino)
sp.on("open", function () {
sp.on('data', function(data) {
console.log("Serial port received data:" + data);
//var result=data.split(" ");//data gets split by " " to get the values
//sendStateToArtikCloud(result[0],result[2],result[1]);//parking,temperature,waterlevel
sendDataToArtikCloud(data);
});
});
process.on('SIGINT', exitClosePins);
I am getting an error on my raspberry pi
enter image description here
Suggest me a solution.
The documentation will tell you that Readline is spelled with a capital R
https://www.npmjs.com/package/serialport#module_serialport--SerialPort.parsers
parser: serialport.parsers.Readline("\n")
~
[TypeError: serialport.parsers.readline is not a function.]
If it has not been resolved yet, try this method.
var serialport = require("serialport")
var SerialPort = serialport.SerialPort;
var sp = new serialport("/dev/ttyACM0"),{
BaudRate: 9600,
parser: new serialport.parsers.Readline("\r\n")
});
I hope your problem is solved.

Beaglebone Black revC

I am connecting BBB and a set of arduinos over the serial port (ttyO2).
I have an array to be sent from BBB to a set of arduinos.
I need to make the BBB sends a request and wait for a reply from one of the arduinos, but if no arduino replies within an interval, the BBB must send the following value in the array.
I have the connection and arduinos ready for their jobs.
The problem is that the BBB will listen on the port and complete the execution of the code at the same time. I need to make it listen for a specific time, if data received=> process it; else complete the following part of code (send the remaining part of the array). This job need to be in a loop.
I have been trying to use setTimeout, recursion, but with no success!
I am using the following code to listen and write on ttyO2:
` var b = require('bonescript');
//opening the serial port
var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort('/dev/ttyO2', {
baudrate: 115200
});
var i = 0;
serialPort.on("open", function () {
console.log('opened');
serialPort.on('data', function(data) {
console.log('data received: ' + data);
serialPort.write( i + "\n", function(){});
});
});
serialPort.on("data", function (data) {
console.log("here: "+data);
});
`
var b = require('bonescript');
//opening the serial port
var SerialPort = require("serialport").SerialPort;
var serialPort = new SerialPort('/dev/ttyO2', {
baudrate: 115200
});
var i = 0;
var waiting_interval = 5000;
var slaves = ["S1", "S2" , "S3", "S4", "S5"];
serialPort.on('open',function my(){
console.log("opened");
serialPort.on('data', function listenToSlaves(data){
console.log("returned: " + data);
});
writeToSlaves();
});
function writeToSlaves(){
// setInterval(serialPort.write(slaves[i], function(){ console.log("I
wrote to slave: " + i)}), 5000);
serialPort.write(slaves[i], function(){ });
console.log("I wrote to slave: " + i);
if(i<slaves.length - 1) i++;
else i=0;
setTimeout(writeToSlaves, waiting_interval);
}

NodeJs Convert 'net' socket to SSL/TLS based socket?

I have following nodejs code running on the server (chat engine). I want to convert this into a secure SSL/TLS based connection. How do i do that ?
In the client side (see below code), everytime i tried to convert this into SSL it gives me a error of "Cross origin request failed." i dont know why ?
NODE.JS Server Side Code
var cluster = require('cluster');
var net = require('net');
var fs = require('fs');
var config = require('./config.js');
var num_processes = 1;//require('os').cpus().length;
if (cluster.isMaster) {
// This stores our workers. We need to keep them to be able to reference
// them based on source IP address. It's also useful for auto-restart,
// for example.
var workers = [];
// Helper function for spawning worker at index 'i'.
var spawn = function (i) {
workers[i] = cluster.fork();
// Optional: Restart worker on exit
workers[i].on('exit', function (worker, code, signal) {
if (config.server.restart_instances_on_crash) {
spawn(i);
logging.log('debug', 'Node instances exited, respawning...');
}
});
};
// Spawn workers.
for (var i = 0; i < num_processes; i++) {
spawn(i);
}
// Helper function for getting a worker index based on IP address.
var worker_index = function (ip, len) {
var s = '';
for (var i = 0, _len = ip.length; i < _len; i++) {
if (ip[i] !== '.') {
s += ip[i];
}
}
return Number(s) % len;
};
/* wait 5 seconds to make sure all the instances are running and initialized */
setTimeout(function () {
// Create the outside facing server listening on our port.
var options = {
pauseOnConnect: true
};
var server = net.createServer(options, function (connection) {
// We received a connection and need to pass it to the appropriate
// worker. Get the worker for this connection's source IP and pass
// it the connection.
var str = connection.remoteAddress;
var ip = str.replace("::ffff:", '');
var worker = workers[worker_index(ip, num_processes)];
worker.send('sticky-session:connection', connection);
}).listen(config.server.listenport);
logging.log('debug', 'Server listening on ' + config.server.listenip + ':' + config.server.listenport + '...');
}, 5000);
process.on('uncaughtException', function (error) {
logging.log('error', 'uncaughtException');
logging.log('error',error.stack);
process.exit(1);
});
} else {
var express = require('express');
var sio = require('socket.io');
var sio_redis = require('socket.io-redis');
var dateandtime = require('./includes/dateandtime.js');
var stats = require('./includes/stats.js');
var helper = require('./includes/helper.js');
// Note we don't use a port here because the master listens on it for us.
var app = new express();
// Don't expose our internal server to the outside.
var server = app.listen(0, 'localhost'),
io = sio(server);
io.set('origins', '*:*');
}
In my Client side i have following code based socket.io JS module. (All these works fine without the SSL connection when using net module only)
Following is the client side javascript code to connect to the node server using socket.io functions.
var root_url = 'http://'+window.location.hostname;
var socket_io = 'http://example.com/js/chat/socket.io-1.3.5.js';
$(document).ready(function () {
$.getScript(socket_io, function () {
socket = io.connect(root_url + ':8440');
... etc
Can only hint you into checking the cors package for crossdomain requests but the deeper issue could be that not everything is running in SSL. (mixed http & https)

Pass Binary Data with WebSocket

I'm writing a Firefox extension and I'm searching to pass a zipped file with a WebSocket (server here). The code is the following for the client side (that send the file):
var ws = new window.WebSocket("ws://localhost:12345");
function sendLogToOtherClient(file){
var zippedFileToSend = zipLogFile(file);
NetUtil.asyncFetch(zippedFileToSend, function(inputStream, status) {
if (!components.isSuccessCode(status)) {
return;
}
var bstream = Cc["#mozilla.org/binaryinputstream;1"].createInstance(Ci.nsIBinaryInputStream);
bstream.setInputStream(inputStream);
var bytes = bstream.readByteArray(bstream.available());
bstream.close();
var encodedData = base64.encode(bytes, "utf-8");
ws.send(encodedData);
});
}
function zipLogFile(fileToZip){
var zippedFile = FileUtils.getFile("ProfD", ["report1.zip"], false);
var zipWriter = CCIN("#mozilla.org/zipwriter;1", "nsIZipWriter");
zipWriter.open(zippedFile, FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE);
zipWriter.addEntryFile("logfile.txt", zipWriter.COMPRESSION_BEST, fileToZip, false);
zipWriter.close();
return zippedFile;
}
And this for Server side (that receive file and write new zipped file):
server = new WebSocketServer(12345);
server.onclient = function(client) {
console.log(client + " connected");
client.onmessage = function(client, msg) {
client.send("Log Received");
var zippedTmpFile = FileUtils.getFile("ProfD", ["report2.zip"], false);
asyncTmpSave(zippedTmpFile, msg, onDone)
};
};
server.connect();
function asyncTmpSave(file, data, callbackDone){
var ostream = FileUtils.openFileOutputStream(file, FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE);
var converter = CCIN('#mozilla.org/intl/scriptableunicodeconverter', "nsIScriptableUnicodeConverter");
converter.charset = 'UTF-8';
var istream = converter.convertToInputStream(data);
NetUtil.asyncCopy(istream, ostream, callbackSaved);
function callbackSaved (status) {
if(callbackDone){
if(status===0)callbackDone( file.path, file.leafName, status); //sucess.
else callbackDone( null, null, status); //failure.
};
}
}
function onDone(path, leafName, statusCode){
console.log([statusCode===0?"OK":"error",path,leafName].join("\n"));
}
I've tryed to pass string and the communication works, and in this case data are passed and the file is created, but the .zip file is corrupted. Do you have any ideas? Thanks
You cannot utf-8 encode random, binary stuff.
WebSockets (and my server) support typed arrays.
So you'll when sending want:
var bytes = new Uint8Array(bstream.available());
bstream.readArrayBuffer(bytes.byteLength, bytes.buffer);
bstream.close();
ws.send(bytes);
And on the receiving end you'll receive an Uint8Array as well.

Categories

Resources