使用localhost android获取套接字连接超时

问题描述 投票:0回答:2

我使用php在本地主机上创建了一个api。这是因为我在postman中测试它运行良好但是当我从android调用url时它给出了套接字连接超时的例外。

它的ampps服务器,无法连接。

这是我的PHP脚本:

    <?php

//echo error
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
ini_set('display_errors', '1');

// require database
require 'database.php';

//get file input
$jsonText = file_get_contents('php://input');

//check params in file
if (empty($jsonText)) {
    $response = array("status" => -1, "message" => "Empty request");
    die(json_encode($response));
}

try{

//decode params in json
$json = json_decode($jsonText);
$mobile_no = $json->mobile_no;
$device_id = $json->device_id;

//init database connection
$database = new Database(Constants::DBHOST, Constants::DBUSER, Constants::DBPASS, Constants::DBNAME);
$dbConnection = $database->getDB();

//query to insert device

$statement = $dbConnection->prepare("INSERT INTO data(mobile_number, device_id)
    VALUES(:mobile_no, :device_id)");
$statement->execute(array(
    "mobile_no" => $mobile_no,
    "device_id" => $device_id
));
    $newId = $dbConnection->lastInsertId();

    if($newId != null)
    {
        $response = array("status" => 1, "message" => "Success");
        die(json_encode($response));
    }
}
catch(PDOException $e) {
    echo $e->getMessage();
}

常量:

<?php

class Constants
{
    const DBNAME = 'UserDevices';
    const DBUSER = 'fsdfsf';
    const DBPASS = 'fsdfsdfs';
    const DBHOST = '192.168.44.1';
}

?>

数据库

    <?php
require 'constants.php';

class Database
{

    private $dbhost;
    private $dbuser;
    private $dbpass;
    private $dbname;


    function Database($dbhost, $dbuser, $dbpass, $dbname)
    {
        $this->dbhost = $dbhost;
        $this->dbuser = $dbuser;
        $this->dbpass = $dbpass;
        $this->dbname = $dbname;

    }

    function getDB()
    {

        $mysql_conn_string = "mysql:host=$this->dbhost;dbname=$this->dbname;charset=utf8";

        try {
            $dbConnection = new PDO($mysql_conn_string, $this->dbuser, $this->dbpass);
            $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $ex) {

            echo($ex->getMessage());
        }

        return $dbConnection;
    }
}

?>

安卓

    String token = tokenPreference.getString("token","");

    if(!token.equals("")) {
        //String cno=preferences.getString("cono",null);
        String[] keys = new String[] {"mobile_no", "device_id"};
        String[] values = new String[] {preferences.getString(Const.DRIVER_MOBILE_NUMBER,""), token};

        final String jsonRequest = SecondUtils.createJsonRequest(keys, values);

        String URL = "http://192.168.44.1/fuelOneTest/insertDevice.php";



        new WebserviceCall(MainDriver.this, URL, jsonRequest, "Loading", true, new AsyncResponse() {
            @Override
            public void onCallback(String response) {
                Log.d("myapp", response);

                //     Toast.makeText(RegisterDriver.this, model.getResponse_desc(), Toast.LENGTH_SHORT).show();

                try {
                    JSONObject jsonObject = new JSONObject(response);

                    // change below condition to 0.. for testing it change to 1
                    if (jsonObject.get("message").equals("Success")) {

                        Log.d("DeviceToken", "Device token inserted.");

                    } else {

                    }
                }catch (JSONException je)
                {
                    je.printStackTrace();
                }
            }
        }).execute();
    }

public class WebserviceCall extends AsyncTask<Void,Void,String> {
// interface for response

AsyncResponse delegate;
private final MediaType URLENCODE = MediaType.parse("application/json;charset=utf-8");
ProgressDialog dialog;
Context context;
String dialogMessage;
boolean showDialog = true;
String URL;
String jsonBody;

public WebserviceCall(Context context, String URL, String jsonRequestBody, String dialogMessage, boolean showDialog, AsyncResponse delegate){
    this.context = context;
    this.URL = URL;
    this.jsonBody = jsonRequestBody;
    this.dialogMessage = dialogMessage;
    this.showDialog = showDialog;
    this.delegate = delegate;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();

    if(Utils.isNetworkAvailable(context)) {


        if (showDialog) {
            dialog = new ProgressDialog(context);
            dialog.setMessage(dialogMessage);
            dialog.show();
        }
    }

        else {

            Utils.showDialog(context, context.getString(R.string.networkWarning));

        }

}


@Override
protected String doInBackground(Void... params) {

    // creating okhttp client
    OkHttpClient client = new OkHttpClient();

   //   client.setConnectTimeout(10L, TimeUnit.SECONDS);
    // creating request body
    RequestBody body;
    if(jsonBody != null) {
        body = RequestBody.create(URLENCODE, jsonBody);
    }else{
        body = null;
    };

        // creating request
        Request request = new Request.Builder()
                .post(body)
                .url(URL)
                .build();

        // creating webserivce call and get response

        try {
            Response response = client.newCall(request).execute();
            String res = response.body().string();
            Log.d("myapp", res);
            return res;

        } catch (IOException e) {
            e.printStackTrace();
        }


    return null;
}


@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    if(dialog != null && showDialog){
        if(dialog.isShowing()){
            dialog.dismiss();
        }
    }
    if(s != null){

        delegate.onCallback(s);
    }else{
        Log.d("myapp",getClass().getSimpleName()+": response null");
    }
}

}

为什么会这样呢?有人可以帮我这个吗?

java php android sockets serversocket
2个回答
0
投票

您没有在Android设备上运行该脚本,是吗?

对此的答案很可能是否定的。意思是它不在localhost(或127.0.0.1)。找到实际拥有该脚本并连接到该设备的设备的内部IP(192.168.x.x)。

套接字超时是因为它无法连接到Android设备,因为那里什么也没有。


0
投票

如果你尝试通过Android模拟器连接,你必须使用10.0.2.2 IP。

通过Genymotion - 10.0.3.2。

如果您使用带有移动互联网的硬件设备,您必须在互联网上了解您的电脑ip,例如使用:https://2ip.ru/

如果您使用Wi-Fi,请通过控制台上的“ipconfig”命令检查网络中的IP

要与套接字连接,您还必须知道服务器使用的端口

© www.soinside.com 2019 - 2024. All rights reserved.