Koblenz
Koblenz

Reputation: 137

Websocket not working on my Android app (with Phonegap Build)

I tried to develop a simple mobile application that connect to a websocket server. I used Phonegap Build to make my Android .apk, here's the html code :

<html>
<head>
<title>Testing websockets</title>
</head>
<body>
<div id="messages"></div>
<script type="text/javascript">
var webSocket = 
  new WebSocket('ws://192.168.82.1:8080/WebSocket/websocket');

webSocket.onerror = function(event) {
  onError(event)
};

webSocket.onopen = function(event) {
  onOpen(event)
};

webSocket.onmessage = function(event) {
  onMessage(event)
};


function onMessage(event) {

    document.getElementById('messages').innerHTML 
    += '<h1 align="center"/>' +"    "+ event.data;   

}

function onOpen(event) {

  document.getElementById('messages').innerHTML 
  += '<h1 align="center"/>connection established';
}

  function onError(event) {
  alert(event.data);
}

</script>
</body>
</html>

The code is working fine on my navigator but the message "connection established" doesn't even appear when I use the Android app. Is there something wrong with this code or does my app need some library ?

PS : I have another code with a button sending a message to the server and receiving a text from it, and of course it's the same problem !

Upvotes: 0

Views: 1744

Answers (1)

Salem
Salem

Reputation: 12986

WebSockets are only supported in WebView after Android 4.4. So if you want to use it in older android versions ,you have some choices:

  • Use a Cordova plugin that provides that functionality. For example, https://github.com/knowledgecode/WebSocket-for-Android (this is just an example, I have never worked with that plugin)

  • Use something like SockJS or socket.io to provide webSockets when supported and fallback to other technologies when not. Please note that using those technologies requires you to use them also in the server

Upvotes: 2

Related Questions