Websocket无法在我的Android应用程序上运行(使用Phonegap Build) [英] Websocket not working on my Android app (with Phonegap Build)

查看:196
本文介绍了Websocket无法在我的Android应用程序上运行(使用Phonegap Build)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图开发一个连接到websocket服务器的简单移动应用程序.我使用 Phonegap Build 制作了Android .apk,这是 html 代码:

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>

该代码在我的导航器上运行正常,但是当我使用Android应用程序时,甚至没有出现连接已建立"消息. 这段代码有什么问题吗?还是我的应用需要一些库?

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:我还有另一个带有按钮的代码,该按钮向服务器发送消息并从中接收文本,当然,这是同样的问题!

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 !

推荐答案

WebSocket仅在Android 4.4之后的WebView中受支持.因此,如果您想在较早的android版本中使用它,则可以选择以下方法:

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)

使用类似 SockJS

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

这篇关于Websocket无法在我的Android应用程序上运行(使用Phonegap Build)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆