Chrome websockets, readystate always on 0 - javascript

I'm trying to use websockets on a website, so first I developed a small and very simple websocket page just to test it.
I have a websocket server running on my localhost, it is based on the python Tornado "Chat" demo. For some reason the chat demo app runs perfectly but I can't seem to use the websocket with my own page although some form of connection is made.
I am testing this using the latest Chromium version, so implementing websockets version 13, which is supported by the Tornado implementation.
So here is the problem:
Load page, js executes and Upgrade request is sent to the server
Server receives request and answers
So here in my understanding Chrome should set readyState = 1 and I should be able to send messages from my page.
Only for some reason it doesn't work, readyState remains 0 and of course if I try to send a message I receive an INVALID_STATE_ERR.
Here are the Headers :
Request:
GET ws://127.0.0.1:8000/chatsocket HTTP/1.1
Origin: http://127.0.0.1
Cookie: _xsrf=9f73731fc2d544df864ce777bef0775a
Connection: Upgrade
Host: 127.0.0.1:8000
Sec-WebSocket-Key: pkwlpY+TtxfgUrm3M4WtTQ==
Upgrade: websocket
Sec-WebSocket-Version: 13
Response:
HTTP/1.1 101 Switching Protocols
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Accept: ur9KL2jBhYB38e2SgwOkjyBlQXk=
Any help is appreciated :)
--- EDIT ---
So I figured it out in the end, if you run into the same problem here is the reason:
WebSocket's readyState is updated when the Thread ENDS !
So running a code like:
var ws = new WebSocket(stuff);
while(ws.readyState==0){};
Will send the browser in an infinite loop...
Running code like:
var ws=new WebSocket(stuff);
do_other_stuf();
Might work, but you wont be able to use WS.
If the code that is supposed to run after the socket opens uses the socket this is the way it will have to be written:
var ws=new WebSocket(stuff);
ws.onopen = new function(){
// some code that need WS to be open
}
// rest of the code that doesn't require WS to be open
A better way to do this would be to let the thread end by using an asynchronous call:
var ws = new WebSocket(stuff);
setTimeout(whatever,500);
function whatever(){
if(ws.readyState==1){
// The code you want to run after WS is open
}
else
setTimeout(whatever,500);
}

In order to trigger some functionality when WebSockets are connected please use callbacks:
var socket = new WebSocket(...);
socket.onopen = function() {
// socket is connected
};
socket.onerror = function() {
// some error happened
};
socket.onmessage = function(evt) {
// you get a message: evt.data
};
Using readyState is well bad thing to do in such case, especially if you have to ask it multiple times (is just unnecessary).
Additionally take in account that each vendor of browsers implements WebSockets with very slight differences (unfortunately), so make sure you test it in most browsers.

Related

Web application using websockets “Could not establish connection. Receiving end does not exist."

Java server, javascript client, no special libraries, plain text HTTP/1.1 and websocket connections.
Server side written (in Eclipse) using JDK 16 and a websocket jar found in Tomcat, version 10.0.2. (Many permutations of other JDKs and websocket jars have also been tried.)
Two web applications. Tomcat 10.0.2 on PC, 10.0.7 on server. Both apps run on Windows 10. Deployed to a Ubuntu 20.04 server. Both programs display the initial HTTP data. One program gets a websocket connection and works, the other fails to get the websocket connection. Both use the same code to calculate the target URL for the websocket connection:
window.onload = function() {
var target = "ws://" + location.host + "/[context]/[endpoint]";
console.log("target: " + target);
try {
if ('WebSocket' in window) {
socket = new WebSocket(target);
} else if ('MozWebSocket' in window) {
socket = new MozWebSocket(target);
} else {
alert('WebSocket is not supported by this browser.');
return;
}
} catch (e) {
console.log("websocket connection exception: " + e.description);
}
...
Where only [context] and [endpoint] differ. Recall that these URLs work on a PC. I believe they are “well-formed”/valid.
Results for the web app that fails:
Firefox:
uncaught exception: Could not establish connection. Receiving end does not exist.
GET ws://35.xxx.xx.xx:8080/Memory/MemoryEndpoint[HTTP/1.1 404 70ms]
Firefox can’t establish a connection to the server at ws://35.xxx.xx.xx:8080/Memory/MemoryEndpoint.
Chrome:
Error handling response: TypeError: Cannot read property 'encrypt' of undefined
at Object.13 (chrome-extension://bkdgflcldnnnapblkhphbgpggdiikppg/public/js/content-scripts/autofill.js:1427:33)
. . .
game.js:31 WebSocket connection to 'ws://xxx.xx.xx.xx:8080/Memory/MemoryEndpoint' failed:
Chrome continues for many lines regarding the 'encrypt' undefined issue. I have no idea what that is about but it might be very relevant. The last line above implies that some reason for the failure might be given on the next line, but it is empty.
Neither browser logs the expected exception text beginning with: "websocket connection exception:".
Tomcat log files are all clean except for some curious entries in localhost__access_log such as:
209.90.225.218 - - [11/Jul/2021:00:43:33 +0000] "HEAD /robots.txt HTTP/1.0" 404 -
And others mentioning /invoker/readonly, /login, /jenkins/login, /nifi/.
The fact that both programs do return results from the Tomcat server tells me that permissions on ports etc are all sufficient. I've also dug into netstat results and the like, reviewed firewall settings, read many many articles and requests for help. (Probably irrelevant because Tomcat does return expected HTTP/1.1 data.) No luck.
I need this program to work. I would pay a cash reward for a solution to this by 07-16-2021, though I don't know how to discretely negotiate that. :-(
Problem resolved, though I don't understand the cause. Recall: the web application ran fine on development PC deployed to Tomcat version 10.0.2, for various JDKs, websocket libraries (including one found in the Tomcat 10.0.7 that had been installed on the VM). The app failed on the Ubuntu VM. A friend installed Tomcat 10.0.8 in the VM. Presto! websockets work.

Check telnet connection with server IP and Port number in JScript

I need to test telnet connection to the server in my local pc. My pc don't have any server side languages like PHP, NodeJS,.. I want to do this in basic JavaScript or chrome extension from latest chrome. I have checked with websocket HTML5. But, it was not working. Here's my code,
<script>
var connection = new WebSocket('ws://10.0.30.1:80');
connection.onopen = function () {
connection.send('Ping'); // Send the message 'Ping' to the server
};
</script>
Lets explain what's my mistake and give me a solution if any other possible.
You can't. Unless you set up a proxy server, a websocket can only communicate with a websocket server.

Getting an error Socket is trying to reconnect to Sails

My Sails version is 0.11.2 and running with port 1337
In assets/js/dependencies/sails.io.js, i can see version as 0.11.0
Below is the client side script.
<script src="http://localhost/project/assets/js/dependencies/sails.io.js"></script>
<script type="text/javascript">
// `io` is available as a global.
// `io.socket` will connect automatically, but at this point in the DOM, it is not ready yet
// (think of $(document).ready() from jQuery)
//
// Fortunately, this library provides an abstraction to avoid this issue.
// Requests you make before `io` is ready will be queued and replayed automatically when the socket connects.
// To disable this behavior or configure other things, you can set properties on `io.sails`.
// You have one cycle of the event loop to set `io.sails.autoConnect` to false before the auto-connection
// behavior starts.
io.socket.get('/hello', function serverResponded (body, JWR) {
// JWR ==> "JSON WebSocket Response"
console.log('Sails responded with: ', body);
console.log('with headers: ', JWR.headers);
console.log('and with status code: ', JWR.statusCode);
// first argument `body` === `JWR.body`
// (just for convenience, and to maintain familiar usage, a la `JQuery.get()`)
});
I am getting the error like
Socket is trying to reconnect to Sails...
When i checked some other posts, there saying something related with sails version.
I tried to change the sails.io.js version to 0.11.2, but still same error.
Is this error have any connection with port ?
Because the response from below request is 404
http://localhost/socket.io/?__sails_io_sdk_version=0.11.2&__sails_io_sdk_platform=browser&__sails_io_sdk_language=javascript&EIO=3&transport=polling&t=1444654910110-52
Response
<p>The requested URL /socket.io/ was not found on this server.</p>
<address>Apache/2.2.22 (Ubuntu) Server at localhost Port 80</address>
Any help what is wrong ?
You're running the Sails app on port 1337, but loading the sails.io.js file from port 80 (because you don't specify another port):
<script src="http://localhost/project/assets/js/dependencies/sails.io.js">
I guess you have an Apache server running on port 80, so it's finding the sails.io.js file and returning it, but then the socket client assumes that it should be connecting on port 80 as well.
Either update your script tag with a port:
<script src="http://localhost:1337/js/dependencies/sails.io.js">
or specify an alternate URL for the socket to connect to, using the following code before the io.socket.get:
io.sails.url = "http://localhost:1337";
The 404 is coming from a client-side socket attempting to connect to the server, which is not accepting socket connections.
if you are not using a socket in your application you need to delete the sails.io.js script.
and below both options didn't work for me but this worked. I deleted the sails.io.js file.

Websocket Server, based on socketo.me not accepting connections from shared internet

I managed to configure a simple websocket server according to this tutorial in AWS EC2 instance and its working fine.
But only from my home internet connection which has a real IP and told as a dedicated internet line.
I tried with a very simple javascript example code from client side (using a HTML page) and it works perfectly if I use that dedicated internet connection from my PC/Mac. (I used autobahn.min.js) above the following script.
var conn = new ab.Session('ws://X.X.X.X:8080',
function() {
console.log("Connection established!");
// To Do: Subscribe with client ID
},
function() {
console.warn('Connection closed!');
},
{'skipSubprotocolCheck': false}
);
but it fails if I run the same simple file/script from under another shared internet connection such as cellular data or something like that. I get the following error in browser console.
WebSocket connection to 'ws://X.X.X.X:8080/ws' failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT example.com Connection closed!
The server is in AWS EC2 instance. Yes, 8080 is enabled under security group. Actually all works fine except client connection goes from some specific types of internet connection based computer.
Thanks in advance for any help!

Faye and Nodejs Issue

Hi currently I'm trying to do a notification feature on a webapp and I decided to use Faye in order to make them live notifications. Now the feature works fine on my local computer, but when somebody else tries to connect to my network, they get a connection refused and faye doesn't work.
Current code working on my local machine:
var http = require('http');
var faye = require('faye');
var server = http.createServer();
var bayeux = new faye.NodeAdapter({mount: '/faye', timeout: 45});
bayeux.attach(server);
server.listen(8000);
I managed to read some other questions related to this issue, and people said to make the server listen to all interfaces by adding: '0.0.0.0' to the server.listen call. When I do this it even stops working on my local machine. Any help will be appreciated!, Nodejs is not the only server running on my machine but the port is open so thats not an issue. I get a get failed request towards the faye message request.

Categories

Resources