1

I want to make a connection between browser (Chrome) and Android phone. I have a web page that should be opened all the time and should wait for a server which starts at a certain event on Android.

My code:

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function waitForSocketConnection(socket, callback){
    setTimeout(
        function () {
            if (socket.readyState === 1) {
                console.log("Connection is made")
                if(callback != null){
                    callback();
                }
                return;

            } else {
                console.log("wait for connection...")
                waitForSocketConnection(socket);
            }

        }, 5); // wait 5 milisecond for the connection...
}
function WebSocketTest()
{
  if ("WebSocket" in window)
  {
     alert("WebSocket is supported by your Browser!");
     // Let us open a web socket
     var ws = new WebSocket("ws://192.168.0.15:8887");
     waitForSocketConnection(ws, function() {alert('callback')})
     ws.onopen = function()
     {
        // Web Socket is connected, send data using send()
        ws.send("Message to send");
        alert("Message is sent...");
     };
     ws.onmessage = function (evt) 
     { 
        var received_msg = evt.data;
        alert("Message is received...");
     };
     ws.onclose = function()
     { 
        // websocket is closed.
        alert("Connection is closed..."); 
     };

  }
  else
  {
     // The browser doesn't support WebSocket
     alert("WebSocket NOT supported by your Browser!");
  }
}
</script>
</head>
<body>
<div id="sse">
   <a href="javascript:WebSocketTest()">Run WebSocket</a>
</div>
</body>
</html>

If I click Run WebSocket when server is not running then I get alert "Connection is closed" and even if I start a server I don't get "Connection is made" on console. It only works when server is running before I click Run WebSocket. How to make it work?

latata
  • 1,703
  • 5
  • 27
  • 57

2 Answers2

1

You'r missing something in WebSocketTest i think...

  • In ws.onclose you should call ws = new WebSocket.. again to reconnect on error/disconnect...

normaly waiting for server to become available goes like this

var ws = new WebSocket(host);
// if no connection is available or error occurred
ws.onclose = function() {
  // wait a bit and retry, don't flood the network ;)
  setTimeout( function(){ ws = new WebSocket(host); }, 100 );
}

also with this you don't have to explicit check the ready state - just put your code in ws.onopen


EDIT:

arr.. tricky to describe.. read the example noted in comment please ;)

DerDu
  • 688
  • 1
  • 13
  • 25
0

I am doing the following to prepare my WebSocket for use in many other places, not just immediately after the WebSocket readyState changes:

// https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep
const sleep = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms));
};

// (inside of async function)...

  const ws = new WebSocket(<webSocketServerUri>);

  let timeToConnect = 0;
  while (ws.readyState !== ws.OPEN) {
    await sleep(1);
    ++timeToConnect;
  };

  console.log('The WebSocket took ' + timeToConnect + ' milliseconds to connect.');

// (inside of async function)...
// ...
// (some other place in the code where 'ws' is accessible)...

  ws.send('my msg');

// (some other place in the code where 'ws' is accessible)...
M. Hays
  • 11
  • 3