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

痴心易碎 提交于 2019-12-12 03:17:37

问题


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 !


回答1:


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



来源:https://stackoverflow.com/questions/38998548/websocket-not-working-on-my-android-app-with-phonegap-build

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!