Dart - How can I handle multiple socket responses? - flutter

I need to constantly query to a server socket four commands stored in the List pollingCommands:
Command1, Command2, Command3 and Command4 which returns Answer1, Answer2, Answer3 and Answer4 respectively.
My approach has been the following:
Socket.connect(ip, port).then((Socket sock) {
_socket = sock;
_socket.listen(
dataHandler,
onError: errorHandler,
onDone: doneHandler,
cancelOnError: false,
);
timer = Timer.periodic(Duration(milliseconds: 100), (timer) {
if (isComplete) {
_socket.write(
Command.pollingQuery(pollingCommands[pollingCycle]),
);
}
});
}).catchError((Object error) {
print("ERROR !");
});
This is the data handler
void dataHandler(data) {
result = String.fromCharCodes(data).trim();
if (isComplete) {
isComplete = false;
//Some action
if (pollingCycle == pollingCommands.length - 1) {
pollingCycle = 0;
isComplete = true;
} else {
pollingCycle++;
isComplete = true;
}
}
}
This approach is working for me if the timer is greater than 500ms but im not geting it to work with higher frequency as the commands does not correspond to their answer.
Any help? Thanks

Related

Flutter - WebRTC: not working on WIFI / works on Mobile Data

I am using Flutter WebRTC for creating P2P video calling.
I have encountered a problem which is related to networking: I have completeled the application but it only works with Mobile Data.
When changing the network to WiFi, it is not working and connection state hangs on Checking
I used Google Community STUN/TURN Servers and Node JS socket.io for signalling purposes. It also works when the mobile is not on same network but only with Mobile Data.
_createPeer() async {
try {
if (_peerConnection != null) return;
navigator.getUserMedia(mediaConstraints).then((stream) {
_localStream = stream;
_localRenderer.srcObject = stream;
});
_peerConnection = await createPeerConnection(configuration, constraints);
_peerConnection.onSignalingState = _onSignalingState;
_peerConnection.onIceGatheringState = _onIceGatheringState;
_peerConnection.onIceConnectionState = _onIceConnectionState;
_peerConnection.onAddStream = _onAddStream;
_peerConnection.onRemoveStream = _onRemoveStream;
_peerConnection.onIceCandidate = _onCandidate;
_peerConnection.onRenegotiationNeeded = _onRenegotiationNeeded;
_peerConnection.addStream(_localStream);
RTCSessionDescription offer =
await _peerConnection.createOffer(_offer_constraints);
_peerConnection.setLocalDescription(offer);
socket.emit('add-student', [
{'room': room, 'offer': offer.sdp}
]);
} catch (e) {
_snackBar(e.toString());
}
}
_onSignalingState(RTCSignalingState state) {
// _snackBar(state.toString());
}
_onIceGatheringState(RTCIceGatheringState state) {
// _snackBar(state.toString());
}
_onIceConnectionState(RTCIceConnectionState state) {
_snackBar(state.toString());
}
_onAddStream(MediaStream stream) {
if (stream == null) {
_snackBar('null');
return;
}
_progressVisible = false;
_buttonsVisible = true;
_remoteRenderer.srcObject = stream;
setState(() {});
}
_onRemoveStream(MediaStream stream) {
_snackBar('remove');
}
_onCandidate(RTCIceCandidate candidate) {
socket.emit('studentCandidate', [
{
'room': room,
'candidate': {
'candidate': candidate.candidate,
'sdpMid': candidate.sdpMid,
'sdpMLineIndex': candidate.sdpMlineIndex
}
}
]);
}
_onRenegotiationNeeded() {
_snackBar('reneg');
}

Node.js named pipe C#

I am trying to make a NodeJS program and a c# communicate but I can't get the communication working. I think it used to work before but after an update, I needed to change the NodeJS code, and since I really don't have much experience with NodeJS I probably messed up something there. Help would be appreciated.
NodeJS code:
logCommand(req, resp) {
const { command } = req;
var PIPE_NAME = "mypipe";
var PIPE_PATH = "\\\\.\\pipe\\" + PIPE_NAME;
var server = net.createServer(function (stream) {
stream.on('data', function (c) {
});
stream.on('end', function () {
server.close();
});
});
server.on('close', function () {
server.close();
})
server.listen(PIPE_PATH, function () {
})
let logfile = fs.createWriteStream(path.join(config.Config.App.filesPath, 'CairossRun.txt'), {
flags: 'a',
autoClose: true
});
let text1 = `error\n\n`
if (resp.win_lose === 1) {
text1 = `Run: Succes\nTypeOfReward: NoRune\nEndOfTransmission\n\n`;
const rewards = resp.changed_item_list ? resp.changed_item_list : [];
if(rewards){
rewards.forEach(reward => {
if (reward.type === 8) {
text1 = `Run: Succces\nTypeOfReward: Rune\nRuneType: ${JSON.stringify(reward.info.rank)}\nRuneSlot: ${JSON.stringify(reward.info.slot_no)}\nRuneSet: ${JSON.stringify(reward.info.set_id)}\nRuneStars: ${JSON.stringify(reward.info.class)}\nEndOfTransmission\n\n`;
}
});
}
}
else {
text1 = `Run: Failed\nnEndOfTransmission\n\n`;
}
server.on('connection', function (stream) {
stream.write(text1);
})
server.on('drain', function (stream) {
stream.write(text1);
})
C# code:
public bool Connecting()
{
Console.WriteLine("connecting");
pipe = new NamedPipeClientStream(".", "mypipe", PipeDirection.In);
try
{
pipe.Connect(5000);
}
catch (TimeoutException e)
{
}
if (pipe.IsConnected)
{
Console.WriteLine("connected");
fileReader = new StreamReader(pipe);
return true;
}
else
return false;
}

Callback is not a function NODEJS

I am trying learn nodejs and stumble upon this error
callback(null, removed);
TypeError: callback is not a function
It is a Steam trade bot, so when it send me an offer, I accept it but after that it crashes. What is wrong?
exports.removeOweNoTitle = (user, callback) => {
let file = 'data/users/' + user + '.json';
if(fs.existsSync(file)) {
let read = fs.createReadStream(file);
let data = "";
read.on('data', (chunk) => {
data += chunk;
});
read.on('end', () => {
let json;
try {
json = JSON.parse(data);
} catch(error) {
return callback(error);
}
let owe = {};
if(json.owe)
owe = json.owe;
else {
callback(null, 0);
return;
}
let removed = 0;
for(let game in owe) {
if(owe[game]) {
removed += owe[game];
owe[game] = 0;
}
}
let write = fs.createWriteStream(file, {flags: 'w'});
exports.clearNotifications(user, () => {
write.write(JSON.stringify(json), (error) => {
if(error)
return callback(error);
write.end();
});
return;
});
write.write(JSON.stringify(json), (error) => {
if(error)
return callback(error);
write.end();
});
write.on("finish", (callback, error) => {
callback(null, removed); //tady nebyl deklarován callback chyběl
});
});
} else {
generateUserFile(user);
callback(new Error('User\'s file is not defined!'), null);
}
}

Why does collection show as blank in console, but available in Meteor server?

I create a function that creates a whole bunch of tasks and it prints them all out out in the server function and displays on the server log. When I run Tasks.find().fetch() in the console, it returns a blank array. What am I doing wrong here? I have a few other objects that appear to be set up the same way and DO show in the console.
let createDummyTasks = function(){
var numberToFake=1000;
var equipment = ["Auto Folding Machine", "Binding Machine",
"Scissor Machine", "Folding Machine",
"Cutting Machine"];
for (let i = 0; i < numberToFake; i++) {
createDummyTask();
}
console.log(Tasks.find().fetch())
function createDummyTask(){
let name = faker.name.jobArea();
let status = randomStatus();
let duration = Math.floor(Math.random() * 40) + 1;
let startDate = faker.date.between('2017-09-10', '2017-09-17');
let endDate = faker.date.between('2017-09-18', '2017-09-30');
let equipment = Equipment.aggregate({$sample: {size: 1}});
// let thisEquipment = equipment[Math.floor(Math.random() * equipment.length)]
Tasks.insert({name: name,
status: status,
duration: duration,
startDate: startDate,
endDate: endDate
}, function(error){
if(error){
console.log("error");
} else {
console.log("success");
}
})
}
}
In 'collections' folder off of app root I have a task.js
Tasks = new Mongo.Collection('tasks');
Tasks.allow({
insert() {
// When we will ALLOW inserts on the client.
return false;
},
update() {
// When we will ALLOW updates on the client.
return false;
},
remove() {
// When we will ALLOW removes on the client.
return false;
}
});
Tasks.deny({
insert() {
// When we will DENY inserts on the client.
return true;
},
update() {
// When we will DENY updates on the client.
return true;
},
remove() {
// When we will DENY removes on the client.
return true;
}
});
and then I subscribe to the items on the client js
// *************************************************************
Template.schedule.onCreated( () => {
Template.instance().subscribe( 'customers' );
Template.instance().subscribe( 'jobs' );
Template.instance().subscribe( 'tasks' );
Template.instance().subscribe( 'equipment' );
});
Template.widget.onRendered(function(){
if(Meteor.isDevelopment){
Meteor.call('populateDummyInfo', (error)=>{
if(error){
console.log(error);
}
})
}
})
I didn't publish....
Meteor.publish('tasks', function () {
return Tasks.find();
});

not returning a socketId

function get_socketId(host,port) {
var socketId = -1;
chrome.sockets.tcp.create({}, function(createInfo) {
chrome.sockets.tcp.connect(createInfo.socketId, host, port, function(result) {
if(result >= 0){
socketId = createInfo.socketId;
console.log(socketId);
return socketId;
}
});
});
return socketId;
}
when this function is called:
console.log(get_socketId("irc.freenode.com", 6667));
always returns -1, while showing for e.x 3 in the console.
what am i doing wrong?
chrome.sockets.tcp.create({}, function(createInfo) {});
is an async function the outter sockeId return will hapen earlier then the inner. So the return is -1 cuz the inner functions are not even called when the socketId at the bottom returns.
One possible solution is to create an async function and pass the socketId variable to the callback:
function get_socketId(host,port, callback) {
var socketId = -1;
chrome.sockets.tcp.create({}, function(createInfo) {
chrome.sockets.tcp.connect(createInfo.socketId, host, port, function(result) {
if(result >= 0){
socketId = createInfo.socketId;
console.log(socketId);
callback(null, socketId); //we pass no error and the socketId to our callback function
} else {
callback('no result', null); //we pass an error
}
});
});
};
//call the function here
get_socketId("irc.freenode.com", 6667, function (err, socketId){
if (err){
console.error(err);
} else { //if no error were passed
console.log(socketId);
}
});
Make your variable in global scope, that will stop all your problems.
var socketId;
function get_socketId(host,port) {
socketId = -1;
chrome.sockets.tcp.create({}, function(createInfo) {
chrome.sockets.tcp.connect(createInfo.socketId, host, port, function(result) {
if(result >= 0){
socketId = createInfo.socketId;
console.log(socketId);
}
});
});
return socketId;
}