Closing WebSocket connection in JavaScript - 1006 error code everytime - javascript

Why does my WebSocket connection always closes with 1006 error code, even when I use .close(1000) or .close(3000).
Interestingly, when using the WebSockets connection with Express.js and Express-ws, this does not happen, only when using our real API. Could it be something the server does? Isn't 1006 local only though?
Any help would be appreciated.
Thanks

This answer says:
Close Code 1006 is a special code that means the connection was closed abnormally (locally) by the browser implementation.
If your browser client reports close code 1006, then you should be looking at the websocket.onerror(evt) event for details.
...

Related

MongoNetworkError: connection 5

Does anyone know what this problem might be?
{ MongoNetworkError: connection 5 to magicalcreature-shard-00-00-jfi8q.mongodb.net:27017 closed
when I run it on my pc everything's fine, everything's connected. But when I run thru heroku it gives me the error.The code on github is the same except I put process.env.MONGOD instead of the connection string. The connection string looks like this:
mongodb+srv://AlwaysRejected:password#magicalcreature-jfi8q.mongodb.net/test?retryWrites=true
I came into this question while facing the same issue, and while its 4 months old, ill reply with what fixed it for me in case anyone else runs into the same issue.
The problem was that mongodb required a whitelist of ips, and since heroku doesn't use a static ip unless you configure an enterprise private space I had to whitelist all ips using 0.0.0.0/0

Websocket can't send/receive messages on Chrome/Firefox, works fine on Microsoft Edge

I'm making a remote debugging tool for Unity(C#), and I've set up a C# WebSocket server in the game that emits Log messages.
The remote debugging client is in JavaScript, on a page served by an http server also created by the game.
I seem to be running into issues sending messages on some browsers, and I'm not sure why. I am running the websocket server on localhost and running the client locally, and I know that kind of stuff is not really liked by chrome/firefox. But the weird thing is that I'm not getting any hard errors or exceptions. Failures seem to fail silently.
I'm pretty certain that the issue is JS/Browser related as the C# websocket server works and receives connections in all cases.
Anyway, here's the socket part of the JS code:
var socket = null;
var host = "ws://"+window.location.hostname;
var port = 55000;
var url = host+":"+port+"/msg";
function CheckSocketStatus()
{
if(socket!=null){
console.log(socket.readyState);
}
}
function CreateSocket()
{
socket = new WebSocket(url);
socket.onopen = function()
{
// // Web Socket is connected, send data using send()
console.log("Socket Open!");
socket.send("Here's a client message for ya!");
};
socket.onmessage = function (evt)
{
var message = evt.data;
console.log("MSG: " + message);
var obj = JSON.parse(message);
console.log(obj)
console.log(obj.type)
if(obj.type == "log"){
console.log("Recieved Log");
handleLogMessage(obj);
}
};
socket.onerror = function()
{
console.log("Error!");
}
socket.onclose = function(event)
{
// websocket is closed.
console.log(event.code);
console.log("Connection is closed...");
socket = null;
};
}
In all cases, when I call CreateSocket() a socket gets created and successfully connects to the server. I also have that CheckSocketStatus() function which returns "1" after the socket opens (Which should mean open/ready to send/receive). After that, here are the results:
Chrome:
Chrome will immediately close after connecting. The only thing I do in the onopen() function is a console.log() and a send(). If I remove the send() then the socket will stay open. I do not receive any messages from the server.
Firefox:
Firefox will keep the socket open indefinitely even if I call the send() function in onopen(). However, the server does not receive any messages from the client and vice versa. I feel like I managed to it to send client->server earlier but I could not reproduce that while testing for this question.
Microsoft Edge:
Weirdly enough, Edge works just fine. I can receive and send messages. Works exactly as intended.
Node Webkit (nw.js):
I'm also trying to write this as a nw.js app. Predictably, as it's running on chromium (or something googly), it produces the same results as Chrome.
So I'm not really sure what's going on. I'm not really a web programmer so intricate http stuff is not really my forte. I'm really hoping it's just a Local file issue with chrome/firefox and that it'll work fine on those platforms if I'm connecting to an external host. I'll try to test this tomorrow at work with some non-localhost server, and I'll update with my findings.
I guess the answer I'm looking for is what these symptoms point to and how I can get chrome/firefox/webkit to work properly.
Also what does Edge do here that the others do not?
Thanks in advance! If you need any more info from me please just ask! I didn't want to overload this question just in case there's a simple answer.
Update:
So I just tried connecting from my laptop to my desktop and the same issues still persist. So to my surprise it's not a local issue. I'm a bit stumped. I might have to look at the server code as well. I've also been told to try to use a wrapper, like socket.io, that might solve some platform dependent issues.I've worked with Socket.io/Unity before but I don't think I was having these issues (I wasn't running a server on the C# side that time, there don't seem to be any good socket.io server implementations on C#, and I'm not sure if socket.io interfaces with normal websockets). So that might point to a problem with my implementation on the C# side.
So I figured it out, thanks to gman. I looked at some of his code and noticed that he used a setting in his WebSocketBehavior class called "Ignore Extensions".
The websocket-sharp documentation has this to say:
"If it's set to true, the service will not return the Sec-WebSocket-Extensions header in its handshake response."
"I think this is useful when you get something error in connecting the server and exclude the extensions as a cause of the error."
So I guess that that header did not jive well with Chrome/Firefox. I'm still doing some testing but this solved the behavior I was seeing with those browsers.
So if you get similar errors, do that!

C# Creating websocket - onmessage function doesn't work

I'have created websocket like this:
Create "Hello World" WebSocket example
I have a problem because server doesn't send message to Client and in JS script function onmessage() is never fired. The connection is closed right after second send() on server is fired or after while. Do you know how to fix it? There is no respectable documentation for websockets and I couldn't find right answer why it doesn't work. Thanks for all answers.
#edit
There is an error after sending second message.
An error: An established connection was aborted by the software in your host.
There is also an error in javascript. When the second message is sending I get an error: Invalid frame header.
I have no idea why the first message with header works but the second with data doesn't.
I solved it. When u use socket server and websocket client you have to create your own frame for sending data back to client and it works fine.

Are browsers supposed to repeat a request if there is no server response after a while?

I have opened asked this question on the Sails project, but it might not be related to Sails at all -- maybe related to Node.js, Express.js or my own code, so I wonder if anyone has ever experienced this:
I have noticed that the browser requests are "replayed" on the server. In order to test it, I did this:
Created a simple controller action that prints "this is a request" on the server -- but does nothing else: it doesn't even send a response to the browser.
When I hit that route, the server console prints "this is a request", as expected.
Keep waiting. The browser keeps looping. After 2.5 minutes, "this is a request" is printed again on the server. Is this an expected behavior?
Worst:
Reload the server.
Hit the route.
"this is a request" is printed on the console.
Now ctrl+c the server to shut it down and right away sails lift it again while the browser is still looping.
The browser will stop, and right after the server is lifted.... "this is a request" is printed on the console.
More info: I am using sails sockets-io and my code has a "reconnect" function:
io.socket.on('disconnect', function(){
socketCleanup();
io.socket.on('connect', function(){
socketConnect();
});
});
This is used to re-subscribe the user socket to special rooms ( io.socket.post(socketRooms... ) but I don't think it would be responsible for these "replays".
If anything of the above is not the expected behavior, could it be possible that, after an upload is cancelled, there is something trying to replay the upload, causing the server to crash?
I am running Sails on Windows 7.
Something I never knew:
node.js page refresh calling resources twice?
Could this all be caused by favicon???
It seems there is a known bug for Chrome regarding favicons causing duplicate requests: https://bugs.chromium.org/p/chromium/issues/detail?id=64810
However, this doesn't seem related, since the second request here is happening 2.5 minutes later. I have tested with Firefox and IE 9 and the issue is valid there.

In NodeJS, how do I re-establish a socket connection with another server that may have gone down?

So, I have a Express NodeJS server that is making a connection with another app via an upagraded WebSocket uri for a data feed. If this app goes down, then obviously the WebSocket connection gets closed. I need to reconnect with this uri once the app comes back online.
My first approach was to use a while loop in the socket.onclose function to keep attempting to make the re-connection once the app comes back online, but this didn't seem to work as planned. My code looks like this:
socket.onclose = function(){
while(socket.readyState != 1){
try{
socket = new WebSocket("URI");
console.log("connection status: " + socket.readyState);
}
catch(err) {
//send message to console
}
}
};
This approach keeps giving me a socket.readyState of 0, even after the app the URI is accessing is back online.
Another approach I took was to use the JavaScript setTimout function to attempt to make the connection by using an exponential backoff algorithm. Using this approach, my code in the socket.onclose function looks like this:
socket.onclose = function(){
var time = generateInterval(reconnAttempts); //generateInterval generates the random time based on the exponential backoff algorithm
setTimeout(function(){
reconnAttempts++; //another attempt so increment reconnAttempts
socket = new WebSocket("URI");
}, time);
};
The problem with this attempt is that if the app is still offline when the socket connection is attempted, I get the following error, for obvious reasons, and the node script terminates:
events.js:85
throw er; // Unhandled 'error' event
Error: connect ECONNREFUSED
at exports._errnoException (util.js:746:11)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1010:19)
I also began using the forever node module to ensure that my node script is always running and to make sure it gets restarted after an unexpected exit. Even though I'm using forever, after a few restarts, forever just stops the script anyway.
I am basically just looking for a way to make my NodeJS server more robust and automatically re-connect with another server that may have gone down for some reason, instead of having to manually restart the node script.
Am I completely off base with my attempts? I am a noob when it comes to NodeJS so it may even be something stupid that I'm overlooking, but I have been researching this for a day or so now and all of my attempts don't seem to work as planned.
Any suggestions would be greatly appreciated! Thanks!
Few suggestions
1) Start using domain which prevents your app from an unexpected termination. Ie your app will run under the domain(run method of domain). You can implement some alert mechanism such as email or sms to which will notify when any error occurs.
2) Start using socket.io for websocket communication, it automatically handles the reconnection. Socket.io uses keep-alive heartbeat and continuously polls from the server.
3) Start using pm2 instead of forever. Pm2 allows clustering for your app which improves the performance.
I think this may improve your app's performance, stability and robustness.

Categories