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?