I am trying to use websites on a website, so first I designed a small and very simple web page to test it.
I have a websocket server running on my localhost, it is based on the Python T Chat Chat demo. For some reason, the chat demo application works fine, but I cannot use websocket with my own page, although some form of connection is being created.
I am testing this using the latest version of Chromium, so I am implementing websockets version 13, which is supported by the Tornado implementation.
So here is the problem:
- The page loads, js executes and the update request is sent to the server
- Server receives request and responses
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 does not work, readyState remains 0 and, of course, if I try to send a message, I get 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
Answer:
HTTP/1.1 101 Switching Protocols Connection: Upgrade Upgrade: websocket Sec-WebSocket-Accept: ur9KL2jBhYB38e2SgwOkjyBlQXk=
Any help is appreciated :)
--- EDIT ---
So, I realized this at the end, if you are facing the same problem, here's why:
WebSocket readyState is updated when Thread ENDS!
So run the code like:
var ws = new WebSocket(stuff); while(ws.readyState==0){};
The browser will be sent in an endless loop ...
Running code, for example:
var ws=new WebSocket(stuff); do_other_stuf();
It may work, but you cannot use WS.
If the code that should be run after the socket is opened uses the socket in such a way that it must be written:
var ws=new WebSocket(stuff); ws.onopen = new function(){
The best way to do this is to allow the end of the stream using an asynchronous call:
var ws = new WebSocket(stuff); setTimeout(whatever,500); function whatever(){ if(ws.readyState==1){