"Uncaught exception: out of memory" in TCP Client for Firefox OS - tcpclient

I'm trying to send some data over TCP connection from my TCP client for Firefox OS. Initially I started with filling loginBytes with the data which should help me to login to the service specified by ip and port (array's size is 28 bytes), now I'm trying to send an empty array. In any case the outcome is the same: in console log of Firefox Web IDE I can see the following message: uncaught exception: out of memory. And among the messages I tried to use for debugging only "Started sending data" is printed. So I come to a conclusion that the failure takes place during the execution of the send command. But what can be wrong with it?
(function() {
var sendButton = document.querySelector('#send');
var notes = document.querySelector('#notes');
var options = {binaryType: 'arraybuffer'};
var socket = navigator.mozTCPSocket.open(ip, port, options);
sendButton.addEventListener('click', function() {
var loginBytes = [];
var Int8View = new Uint8Array(loginBytes);
socket.ondata = function(event) {
console.log("Started receiving data");
console.log(event.data);
console.log("Received successfully");
}
socket.onerror = function(event) {
console.log("Everything is bad");
}
console.log("Started sending data");
socket.send(Int8View);
console.log("Sent successfully");
});
})();

I think
var Int8View = new Uint8Array(loginBytes)
needs to be changed to:
var Int8View = new Uint8Array(loginBytes).buffer
Uint8Array by itself does not return an ArrayBuffer object.

Related

App Maker: Sending Email, client script to server script function not working. Failed due to illegal value in property: a

I am new to AppMaker but I have developer experience.
The application is a Project Tracker Application
What I expect to happen: When creating a project the user uses a User Picker to select the users associated with that project. When the project is created I want to email the users associated with that project.
The issue: On clicking the Add button addProject(addButton) client script function is called.
Inside this function sendEmailToAssignees(project, assignees) is called which should reach out to the Server script and run the notifyAboutProjectCreated(project, assignees) but that is not happening.
Things to know: With logging I never reach 'Trying to send email' so I seem to never reach my server script. Also, On client script when I comment out sendEmailToAssignees function everything runs smooth. I have looked at this documentation as a resource so I feel my implementation is okay. https://developers.google.com/appmaker/scripting/client#client_script_examples
The final error message I get is:
Failed due to illegal value in property: a at addProject
(AddProject:110:24) at
AddProject.Container.PanelAddProject.Form1.Spring.ButtonAdd.onClick:1:1
Am I missing something here? Any help would be greatly appreciated. Thank you!
Client Script
function sendEmailToAssignees(project, assignees) {
google.script.run
.withSuccessHandler(function() {
console.log('Sending Email Success');
}).withFailureHandler(function(err) {
console.log('Error Sending Email: ' + JSON.stringify(err));
})
.notifyAboutProjectCreated(project, assignees);
}
function addProject(addButton) {
if (!addButton.root.validate()) {
return;
}
addButton.datasource.createItem(function(record) {
var page = app.pages.AddProject;
var pageWidgets = page.descendants;
var trainees = pageWidgets.AssigneesGrid.datasource.items;
var traineesEmails = trainees.map(function(trainee) {
return trainee.PrimaryEmail;
});
record.Assignee = traineesEmails.toString();
var assignees = traineesEmails.toString();
var project = record;
updateAllProjects(record);
console.log('update all projects done');
sendEmailToAssignees(project, assignees);
console.log('Send Email done');
if (app.currentPage !== app.pages.ViewProject) {
return;
}
gotoViewProjectPageByKey(record._key, true);
});
gotoViewProjectPageByParams();
}
Server Script
function notifyAboutProjectCreated(project, assignees) {
console.log('Trying to send email');
if (!project) {
return;
}
var settings = getAppSettingsRecord_()[0];
if (!settings.EnableEmailNotifications) {
return;
}
var data = {
appUrl: settings.AppUrl,
assignee: project.Assignee,
owner: project.Owner,
startDate: project.StartDate,
endDate: project.EndDate,
jobType: project.Type,
jobId: project.Id
};
// Email Subject
var subjectTemplate = HtmlService.createTemplate(settings.NotificationEmailSubjectJob);
subjectTemplate.data = data;
var subject = subjectTemplate.evaluate().getContent();
// Email Body
var emailTemplate =
HtmlService.createTemplate(settings.NotificationEmailBodyJob);
emailTemplate.data = data;
var htmlBody = emailTemplate.evaluate().getContent();
console.log('About to send email to:', assignees);
sendEmail_(null, assignees, subject, htmlBody);
}
The reason you are getting this error is because you are trying to pass the client "project record" to the server. If you need to access the project, then pass the record key to the server and then access the record on the server using the key.
CLIENT:
function sendEmailToAssignees(project, assignees) {
var projectKey = project._key;
google.script.run
.withSuccessHandler(function() {
console.log('Sending Email Success');
}).withFailureHandler(function(err) {
console.log('Error Sending Email: ' + JSON.stringify(err));
})
.notifyAboutProjectCreated(projectKey , assignees);
}
SERVER:
function notifyAboutProjectCreated(projectKey, assignees) {
console.log('Trying to send email');
var project = app.models.<PROJECTSMODEL>.getRecord(projectKey);
if (!project) {
return;
}
//Rest of the logic
}
The project record object in the client is not the same as the project record object in the server; hence the ilegal property value error.

Google Speech API streaming audio from websocket

I am trying to get a final speech transcription/recognition result from a Fleck websocket audio stream. The method OnOpen executes code when the websocket connection is first established and the OnBinary method executes code whenever binary data is received from the client. I have tested the websocket by echoing the voice into the websocket and writing the same binary data back into the websocket at the same rate. This test worked so I know that the binary data is being sent correctly (640 byte messages with a 20ms frame size).
Therefore, my code is failing and not the service. My aim is to do the following:
When the websocket connection is created, send the initial audio config request to the API with SingleUtterance == true
Run a background task that listens for the streaming results waiting for isFinal == true
Send each binary message received to the API for transcription
When background task recognises isFinal == true, stop current streaming request and create a new request - repeating steps 1 through 4
The context of this project is transcribing all single utterances in a live phone call.
socket.OnOpen = () =>
{
firstMessage = true;
};
socket.OnBinary = async binary =>
{
var speech = SpeechClient.Create();
var streamingCall = speech.StreamingRecognize();
if (firstMessage == true)
{
await streamingCall.WriteAsync(
new StreamingRecognizeRequest()
{
StreamingConfig = new StreamingRecognitionConfig()
{
Config = new RecognitionConfig()
{
Encoding = RecognitionConfig.Types.AudioEncoding.Linear16,
SampleRateHertz = 16000,
LanguageCode = "en",
},
SingleUtterance = true,
}
});
Task getUtterance = Task.Run(async () =>
{
while (await streamingCall.ResponseStream.MoveNext(
default(CancellationToken)))
{
foreach (var result in streamingCall.ResponseStream.Current.Results)
{
if (result.IsFinal == true)
{
Console.WriteLine("This test finally worked");
}
}
}
});
firstMessage = false;
}
else if (firstMessage == false)
{
streamingCall.WriteAsync(new StreamingRecognizeRequest()
{
AudioContent = Google.Protobuf.ByteString.CopyFrom(binary, 0, 640)
}).Wait();
}
};
.Wait() is a blocking call being called in an async/await. They don't mix well and can lead to deadlocks.
Simply keep the code async all the way through
//...omitted for brevity
else if (firstMessage == false) {
await streamingCall.WriteAsync(new StreamingRecognizeRequest() {
AudioContent = Google.Protobuf.ByteString.CopyFrom(binary, 0, 640)
});
}

Signalr - endless $.connection.hub.disconnected event?

I'm using Signalr 2.2.1 with a successful websocket connection.
Here are the events for different states : ( simplified for brevity)
var hub = $.connection.moveShapeHub;
$.connection.hub.start().done(function ()
{
console.log("hub started successfully");
}).fail(function () { console.log('Could not Connect!'); });
$.connection.hub.disconnected(function ()
{
$.connection.hub.start();
console.log('Connection disconnected')
});
My app is working fine as expected.
But look what happen when I disable the network card ( I access my computer not via localhost but via dynamic dns which goes to the world and then comes back to my computer)
At first you can see websocket connection error (I see it multiple times)
WebSocket connection to
'ws://xxxxxx.ddns.net/signalr/reconnect?transport=webSockets&messageId=d-C68A95E5-g%2C1&clientProtocol=1.5&connectionToken=%2FDJL8eAtVtSA3XKeap4Js3IrbkCm56C%2FWKCQtApGiMroWAgnzNoRHmJ0Y2LpIdWWWL%2BfY3dXvJqYHFfby1XYii0ibPpKM55PQuZyf9aH4k9JHIT79lWoMWBasIpa9Gjk&connectionData=%5B%5D&tid=2'
failed: Error in connection establishment:
net::ERR_INTERNET_DISCONNECTED
And then you see endless calls(!!!) to the negotiate
http://xxxx.ddns.net/signalr/negotiate?clientProtocol=1.5&connectionToken=%2FDJL8eAtVtSA3XKeap4Js3IrbkCm56C%2FWKCQtApGiMroWAgnzNoRHmJ0Y2LpIdWWWL%2BfY3dXvJqYHFfby1XYii0ibPpKM55PQuZyf9aH4k9JHIT79lWoMWBasIpa9Gjk&connectionData=%5B%7B%22name%22%3A%22moveshapehub%22%7D%5D&_=1485811277855
Wait ~15 seconds to see the endless loop :
Question
How can I fix those endless calls ? Or alternatvly - increase delay in those "negotiate calls" -say every 2 seconds ( instead of blazing fast endlessly 0.1 seconds)
Edit
I've changed this code :
$.connection.hub.disconnected(function ()
{
$.connection.hub.start();
console.log('Connection disconnected')
});
to this (remove hub start):
$.connection.hub.disconnected(function ()
{
console.log('Connection disconnected')
});
And now I see only this message :
But now I'm losing all the basic idea of "trying restart connecting" in case of disconnect. So I ask again is there any reasonable solution or at least trying "restart the connection every 2 seconds" ?
negotiate is the first request a SignalR client sends to establish a connection. You are trying to start the connection as soon as it gets disconnected in the disconnected event handler. Because the network is down negotiate fails and the disconnected event is invoked and you try to start the connection again.
The documentation shows how to do it with the timeout:
$.connection.hub.disconnected(function() {
setTimeout(function() {
$.connection.hub.start();
}, 5000); // Restart connection after 5 seconds.
});
The answer to all issues of SR connections is check and persist connection status on each server request. I have created a method that takes the proxy method as a parameter and fires the proxy method after establishing the hub connection is available.
call the method using SR_Connection.execute.
When it has established the connection is commits the execution of the request.
function cancel(){
SR_Connection.execute('SRProxy.server.Cancel', uniqueID);
}
var SR_Connection = (function () {
//Start of the Return Statement
return {
execute: function (method, params) {
if ($.connection.hub && $.connection.hub.state === $.signalR.connectionState.disconnected) {
$.connection.hub.start().done(function () {
SR_Connection.commit(method, params);
});
}
else {
SR_Connection.commit(method, params);
}
},
commit: function (method, params) {
var namespaces = method.split("."),
context;
if (typeof (window) == "undefined") {
context = global;
} else {
context = window;
}
var functionToExecute = namespaces.pop();
for (var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
context[functionToExecute](params);
}
};//End of the Return Statement
})();

Using signalR to update Winforms UI

I have a form that was created on it's own UI thread running in the system tray which I need to manipulate with a signalR connection from the server which I believe to be running on a background thread. I'm aware of the need to invoke controls when not accessing them from their UI thread. I am able to manipulate (make popup in my case) using the following code that is called on form load but would like a sanity check as I'm fairly new to async:
private void WireUpTransport()
{
// connect up to the signalR server
var connection = new HubConnection("http://localhost:32957/");
var messageHub = connection.CreateProxy("message");
var uiThreadScheduler = TaskScheduler.FromCurrentSynchronizationContext();
var backgroundTask = connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
Console.WriteLine("There was an error opening the connection: {0}", task.Exception.GetBaseException());
}
else
{
Console.WriteLine("The connection was opened successfully");
}
});
// subscribe to the servers Broadcast method
messageHub.On<Domain.Message>("Broadcast", message =>
{
// do our work on the UI thread
var uiTask = backgroundTask.ContinueWith(t =>
{
popupNotifier.TitleText = message.Title + ", Priority: " + message.Priority.ToString();
popupNotifier.ContentText = message.Body;
popupNotifier.Popup();
}, uiThreadScheduler);
});
}
Does this look OK? It's working on my local machine but this has the potential to be rolled out on every user machine in our business and I need to get it right.
Technically you should hook up to all notifications (using On<T>) before you Start listening. As far as your async work I'm not quite sure what you were trying to do, but for some reason your chaining the notification to your UI in On<T> to the backgroundTask variable which is the Task that was returned to you by the call to Start. There's no reason for that to be involved there.
So this is probably what you want:
private void WireUpTransport()
{
// connect up to the signalR server
var connection = new HubConnection("http://localhost:32957/");
var messageHub = connection.CreateProxy("message");
var uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
// subscribe to the servers Broadcast method
messageHub.On<Domain.Message>("Broadcast", message =>
{
// do our work on the UI thread
Task.Factory.StartNew(
() =>
{
popupNotifier.TitleText = message.Title + ", Priority: " + message.Priority.ToString();
popupNotifier.ContentText = message.Body;
popupNotifier.Popup();
},
CancellationToken.None,
TaskCreationOptions.None,
uiTaskScheduler);
});
connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
Console.WriteLine("There was an error opening the connection: {0}", task.Exception.GetBaseException());
}
else
{
Console.WriteLine("The connection was opened successfully");
}
});
}

Keep run into "ETIMEOUT, Timeout while contacting DNS servers" error when making http request in node.js

This error happens whenever the node process make a http request to get user's information from a web API.
The scenario is :
I'm running a TCP server using node, and when it get "login" request from a client, it will send a http GET request to another web API to retrieve the user's information.
While users increasing, the node process starts to throw the "ETIMEOUT" error when retrieving user's info. And once if the error happened, all the request after that will throw the same error.
I've tried to perform the same request with wget but everything is fine, so I think maybe it's not a network problem.
And strangely, after increasing the open file limit to 10,0000 using ulimit -n, it goes well until the next level user increment.
The fetch function is here:
fetchUserInfo = function(callback) {
var http = require('http');
var opt = {
agent: false,
host: 'www.someapi.net',
port: 80,
path: '/userInfo.php'
}
var body = '';
var req = http.request(opt, function(res) {
res.setEncoding('utf8');
res.on('data', function(chunk){
body += chunk;
});
res.on('end', function() {
if(callback) {
callback(body);
}
});
});
req.on('error', function(e) {
sys.log("User info fetch error: " + e.message);
if(callback) {
callback();
}
});
req.end();
}
My environment is Debian GNU/Linux 6.0 with node v0.4.10.

Resources