Question:
I want to connect to my web socket that put on amazone instance with some ip. I can connect my web socket with some ip and port with google rest client app and its working very well.
Screen Shot :
But if i want to connect this with java script it can not connect. This is working fine before 2-3 month. i have not change and thing but its not working now.
If i want to connect with firefox it produce an error.
Here is my code :-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
function init() { var host = "ws://XX.XX.XXX.XXX:XXXX"; // SET THIS TO YOUR SERVER try { var socket = new WebSocket(host); // alert('WebSocket - status ' + socket.readyState); log('WebSocket - status ' + socket.readyState); socket.onopen = function (msg) { alert('open'); alert("Welcome - status " + this.readyState); log("Welcome - status " + this.readyState); if (this.readyState != 1) { reconnect(); } }; socket.onmessage = function (msg) { // alert("Received: " + msg.data); log("Received: " + msg.data); }; socket.onclose = function (msg) { // alert("Disconnected - status " + this.readyState); log("Disconnected - status " + this.readyState); }; } catch (ex) { alert(ex); log(ex); } $("msg").focus(); } |
This is alerting status 0 and error show in console :-
1 2 3 4 5 |
Firefox can't establish a connection to the server at ws://XX.XX.XXX.XXX:XXXX. var socket = new WebSocket(host); |
Answer:
I’d try your code and for me is working just fine, I’d test it with this webpage: https://www.websocket.org/echo.html , maybe could be helpful for testing purposes. But also i found this question: websocket-rails, websocket handshake error , maybe also help.
However i’d just change the host in your code to this:”ws://echo.websocket.org”, and everything works without problems.
Hope you find a solution and that this info was of any help. Here’s your code that i used for the test:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
function init() { var host = "ws://echo.websocket.org"; try { var socket = new WebSocket(host); alert('WebSocket - status ' + socket.readyState); socket.onopen = function (msg) { alert('open'); alert("Welcome - status " + this.readyState); if (this.readyState != 1) { reconnect(); } }; socket.onmessage = function (msg) { alert("Received: " + msg.data); }; socket.onclose = function (msg) { alert("Disconnected - status " + this.readyState); }; } catch (ex) { alert(ex); } $("msg").focus(); } |
*Sorry for my bad english.