简体   繁体   English

Android Web 服务器 nanohttpd - 无法从同一设备上的浏览器连接

[英]Android web server nanohttpd - cannot connect from browser on same device

I have attempted to set up a simple web server on Android using the nanohttpd demo application without modification.我尝试使用 nanohttpd 演示应用程序在 Android 上设置一个简单的 Web 服务器,而无需修改。 The Android devices that I am using are running Android 4.0.3.我使用的 Android 设备运行的是 Android 4.0.3。

I am able to access the web server from other devices, but I am unable to connect to the web server from a browser (Firefox, Chrome, and the native Android browser) on the same Android device that the web server is running.我可以从其他设备访问 Web 服务器,但无法从运行 Web 服务器的同一 Android 设备上的浏览器(Firefox、Chrome 和本机 Android 浏览器)连接到 Web 服务器。

I have tried a variety of addresses and port combinations without success (localhost, 127.0.0.1, 10.0.0.2, the actual assigned IP address, port 8080, 8082).我尝试了多种地址和端口组合都没有成功(localhost,127.0.0.1,10.0.0.2,实际分配的IP地址,端口8080,8082)。 I have also tried having the nanohttpd application bind directly to 127.0.0.1, without success either.我也试过将 nanohttpd 应用程序直接绑定到 127.0.0.1,但也没有成功。 I have verified that I can 'ping' the addresses using a terminal application on the Android device, so it looks like the network connectivity is fine.我已经验证我可以使用 Android 设备上的终端应用程序“ping”地址,因此看起来网络连接正常。

Is there a restriction on Android that will prevent a browser from connecting to the local web server instance, and if so, is there a configuration setting or permission that needs to be modified to allow this to work? Android 上是否存在阻止浏览器连接到本地 Web 服务器实例的限制,如果是,是否需要修改配置设置或权限才能使其正常工作?

1) You need to grant internet permission in AndroidManifest.xml. 1) 您需要在 AndroidManifest.xml 中授予互联网权限。

<uses-permission android:name="android.permission.INTERNET" />

2) Also the port 80 will not be available without root. 2)如果没有root,80端口也将不可用。

See this question for more information.有关更多信息,请参阅此问题

3) Disable any VPN or proxy app or data compression on your device 3) 在您的设备上禁用任何 VPN 或代理应用程序或数据压缩

Through a bunch of trial and error, I believe that I have a handle on what is happening.通过一系列的反复试验,我相信我已经掌握了正在发生的事情。 When I switch from the web server application to the browser to try the request, the web server application is suspended and therefore will not accept the connection.当我从 Web 服务器应用程序切换到浏览器尝试请求时,Web 服务器应用程序被挂起,因此不会接受连接。 I had assumed that the applications were running in the background, but apparently that is not the case.我曾假设应用程序在后台运行,但显然情况并非如此。

I'll explore how to run the web server as a background service and see where that takes me.我将探索如何将 Web 服务器作为后台服务运行,看看这会将我带到哪里。

After embedding the nanohttpd web server inside an Android service, all is working as I had originally intended.将 nanohttpd Web 服务器嵌入到 Android 服务中后,一切都按我最初的预期工作。

将请求 url 更改为http://localhost:port,或者如果您想在模拟器上使用 localhost 的 IP 地址,您可以使用此处的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM