Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 通訊實作:HTTP 搭配 Socket 的雙段式控制

這個範例示範一種常見的兩段式架構:Android 手機以 HTTP POST 把資料送到開發板上的 Apache,再由 PHP 轉成 Socket 連線,把指令丟給真正負責控制的服務。開發板端 phpinfo 的關鍵資訊如下:

System            Linux ShiGuang 2.6.32.2-FriendlyARM #2 armv4tl
Configure Command './configure' '--prefix=/usr/local/php_arm' \
                  '--host=arm-linux' '--target=arm-linux' '--enable-sockets'
DOCUMENT_ROOT     /usr/local/apache_arm/htdocs
HTTP_HOST         192.168.1.120

編譯 PHP 時特別加上了 --enable-sockets,否則後面的 socket 函式全部不可用。

開發板端:post_datas.php

<?php
@header("content-type:text/html; charset=utf-8");
error_reporting(E_ALL);
set_time_limit(0);

$user   = $_REQUEST['user'];
$passed = $_REQUEST['passwd'];
$para   = $_REQUEST['para'];

$service_port = 9090;
$address      = "192.168.1.97";

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket < 0) {
    echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n";
}

$result = socket_connect($socket, $address, $service_port);
if ($result < 0) {
    echo "socket_connect() failed: reason: " . socket_strerror($result) . "\n";
}

$in = $user . $passed . $para;

$result = socket_write($socket, $in, strlen($in));
if (!$result) {
    echo "socket_write() failed: reason: " . socket_strerror($socket) . "\n";
}

while ($out = socket_read($socket, 256)) {
    echo $out;
    break;
}

socket_close($socket);
?>

這支程式撿起三個參數,把它們串成一行文字,往 9090 連接埠的 Socket 服務送出,再把回應印回瀏覽器。set_time_limit(0) 是必要的,因為 Socket 溝通可能會等上一段時間。

手機端:Mini2440Activity.java

package sg131971.mini2440;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Mini2440Activity extends Activity {

    public class myButtonListener implements OnClickListener {

        private HttpResponse response;
        private String tmpString;

        public void onClick(View arg0) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("https://192.168.1.123/post_datas.php");

            try {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
                nameValuePairs.add(new BasicNameValuePair("user", "root"));
                nameValuePairs.add(new BasicNameValuePair("passwd", "shiguang"));
                nameValuePairs.add(new BasicNameValuePair("para", "58402F01"));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                response = httpclient.execute(httppost);
                tmpString = EntityUtils.toString(response.getEntity());
                System.out.print(tmpString);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private Button myButton;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        myButton = (Button) findViewById(R.id.myButton);
        myButton.setOnClickListener(new myButtonListener());
    }
}

按下按鈕後,程式以 POST 送出 user、passwd、para 三個欄位,其中 para 就是實際要傳給硬體的指令碼。別忘了在 AndroidManifest.xml 加上 INTERNET 權限,否則請求會直接失敗。

為什麼要繞這一圈

直接讓手機開 Socket 連到控制服務看似更省事,但實際上讓 Apache 居中反而更實際:手機只認得一個固定的 HTTP 端點,不受內部服務位址變動影響;權限與帳號驗證可以集中在 PHP 層處理;而 Socket 那端就能專心做指令解析,不必兼顧 HTTP 的封包細節。這種「HTTP 對外、Socket 對內」的分層,在嵌入式物聯網專案裡相当常見。

Copyright © Linux教程網 All Rights Reserved