【问题标题】:application failed to connect to server (python, flask, android studio)应用程序无法连接到服务器(python、flask、android studio)
【发布时间】:2020-06-25 08:35:11
【问题描述】:

我一直在尝试此链接here 中的一些代码。 这是如何使用flask将android连接到python的部分。代码在服务器中运行良好。当我尝试运行 android 应用程序时,它运行良好,直到我单击“连接到服务器”按钮时,结果总是无法连接。 android studio中没有错误

layout application

这是python代码

import flask

app = flask.Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def handle_request():
    return "Flask Server & Android are Working Successfully"

app.run(host="0.0.0.0", port=5000, debug=True)

这是python代码中的终端。

 * Serving Flask app "flaskcoba1" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 189-748-501
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

我尝试使用从 cmd 到我的移动设备的 ping 来测试连接以检查连接,它已经连接。

这是main.activity

package com.example.flaskcoba;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void connectServer(View v){
        EditText ipv4AddressView = findViewById(R.id.IPAddress);
        String ipv4Address = ipv4AddressView.getText().toString();
        EditText portNumberView = findViewById(R.id.portNumber);
        String portNumber = portNumberView.getText().toString();

        String postUrl= "http://"+ipv4Address+":"+portNumber+"/";

        String postBodyText="Hello";
        MediaType mediaType = MediaType.parse("text/plain; charset=utf-8");
        RequestBody postBody = RequestBody.create(mediaType, postBodyText);

        postRequest(postUrl, postBody);
    }

    public void postRequest(String postUrl, RequestBody postBody) {

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(postUrl)
                .post(postBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // Cancel the post on failure.
                call.cancel();

                // In order to access the TextView inside the UI thread, the code is executed inside runOnUiThread()
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        TextView responseText = findViewById(R.id.responseText);
                        responseText.setText("Failed to Connect to Server");
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                // In order to access the TextView inside the UI thread, the code is executed inside runOnUiThread()
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        TextView responseText = findViewById(R.id.responseText);
                        try {
                            responseText.setText(response.body().string());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }

}

这是布局代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout   xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="IPv4 Address" />
        <EditText
            android:layout_weight="4"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/IPAddress"
            android:text="192.168.1.7" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="Port Number" />
        <EditText
            android:layout_weight="4"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/portNumber"
            android:text="5000"/>
    </LinearLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Connect to Server"
        android:onClick="connectServer"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Message from the Server ..."
        android:id="@+id/responseText" />



</LinearLayout>

终于在logcat中找到错误

2020-06-29 13:28:46.182 3001-3001/? E/IptablesRestoreController: [iptables debug]iptables-restore execute *filter
    -nvx -L tetherctrl_counters
    COMMIT
2020-06-29 13:28:46.186 3001-3001/? E/IptablesRestoreController: [iptables debug]iptables-restore execute done, res : 0
2020-06-29 13:28:46.186 3001-3001/? E/IptablesRestoreController: [iptables debug]iptables-restore execute *filter
    -nvx -L tetherctrl_counters
    COMMIT
2020-06-29 13:28:46.190 3001-3001/? E/IptablesRestoreController: [iptables debug]iptables-restore execute done, res : 0
2020-06-29 13:28:57.283 3287-3768/? E/Watchdog: !@Sync 718 [2020-06-29 13:28:57.283] FD count : 517
2020-06-29 13:31:46.659 3645-4181/? E/ImsAdaptorImpl: setSSACInfo : ImsAdaptorImpl.
2020-06-29 13:31:46.661 3889-4332/? E/EPDG -- SIM0 [RILRECEIVER]: Incorrect EpdgIilIpcMessage IPC Message -- not initialized
2020-06-29 13:31:46.663 3645-4181/? E/ImsAdaptorImpl: setSSACInfo : ImsAdaptorImpl.
2020-06-29 13:31:46.664 3889-4332/? E/EPDG -- SIM0 [RILRECEIVER]: Incorrect EpdgIilIpcMessage IPC Message -- not initialized
2020-06-29 13:31:46.670 3889-4332/? E/EPDG -- SIM0 [RILRECEIVER]: RX [NET_REGIST] -- RESPONSE -- not initialized

请帮我修复错误

【问题讨论】:

  • 我们看不到客户端使用的 ip 地址。
  • host="127.0.0.1" 我不会将它绑定到本地主机。请尝试使用本地局域网 IP。或者也许 0.0.0.0 对所有人开放。
  • 认为 onFailure() 和 onResponse() 中不需要 runOnUiThread()。
  • 检查这个答案(stackoverflow.com/a/62535200/12368419)它可能有用
  • 客户端使用服务器的ip地址,在android应用中输入。我之前尝试过使用 host="0.0.0.0" ,但是当我在浏览器上查看时,它说“无法访问站点”。因此我使用了 host="127.0.0.1" @blackapps

标签: python android flask


【解决方案1】:

改变这一行:

app.run(host="0.0.0.0", port=5000, debug=True)

这应该是公认的答案。有关为什么 0.0.0.0 有效而 localhost 或 127.0.0.1 无效的更多信息 - check this answer

相关位:

0.0.0.0 有几个不同的含义,但在这种情况下,当服务器被告知监听 0.0.0.0 时,这意味着“监听每个可用的网络接口”。从服务器进程的角度来看,IP 地址为 127.0.0.1 的环回适配器看起来就像机器上的任何其他网络适配器一样,因此被告知侦听 0.0.0.0 的服务器也将接受该接口上的连接。

【讨论】:

  • 我之前尝试过使用 host="0.0.0.0",但是当我在浏览器上查看时显示“无法访问站点”。我不知道为什么。因此我使用了 host="127.0.0.1"
  • @AtnaDiafahma 您是否正在使用物理 android 设备上的浏览器访问http://0.0.0.0/ 上的桌面烧瓶应用程序?
  • 我明白了,抱歉,我想我也误解了这一点。我再次尝试在服务器中使用 0.0.0.0,使用服务器的本地 IP 地址访问,它可以在 android 浏览器中运行,谢谢。但它仍然无法在android应用程序中运行
  • 你看过这个post 吗?
  • 我认为这种方式适用于安卓模拟器,而我使用的是物理安卓设备
【解决方案2】:

我认为您的代码没有任何问题,所以我假设您输入了错误的 IP 地址。如果您在 Windows 上,请在搜索中输入 wifi 设置

类似的步骤适用于 linux

输入您在那里找到的 IPv4 地址,并确保在您的烧瓶应用程序中允许远程连接类似于 app.run(host='0.0.0.0')

【讨论】:

  • 我输入了正确的IP地址。当我在我的 android 浏览器中访问时,它可以工作。但是当我访问我的 android 应用程序时,它说“连接失败”
猜你喜欢
  • 2021-04-22
  • 2018-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-21
  • 1970-01-01
  • 2016-08-09
  • 1970-01-01
相关资源
最近更新 更多