Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 用戶端與電腦伺服器端的 Socket 連線實作

編輯:關於 Android 程式設計

本文示範如何讓 Android 手機作為用戶端,透過 Socket 連上電腦上的 Java 伺服器,雙方互相傳送訊息。這是最基礎的 TCP 通訊範例,很適合作為理解網路連線的起點。

一、電腦端伺服器

伺服器先在 1000 埠監聽,接受連線後讀取一行訊息,加上前綴再回傳給用戶端:

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer {
    public static void main(String[] args) throws Exception {
        ServerSocket server = new ServerSocket(1000);
        Socket clink = server.accept();
        PrintStream out = new PrintStream(clink.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(clink.getInputStream()));
        StringBuffer bu = new StringBuffer();
        bu.append("Android: ");
        bu.append(in.readLine());
        out.println(bu);

        in.close();
        out.close();
        clink.close();
        server.close();
    }
}

二、Android 用戶端

第一步:編寫版面配置 main.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/send"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="連接ServerSocket程序" />

    <TextView
        android:id="@+id/info"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="等待程序的連接" />

</LinearLayout>

第二步:撰寫 Java 程式

public class ActivityMain extends Activity {
    private Button button;
    private TextView textView;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        button = (Button) this.findViewById(R.id.send);
        textView = (TextView) this.findViewById(R.id.info);
        button.setOnClickListener(new SendOnclickListener());
    }

    class SendOnclickListener implements OnClickListener {
        public void onClick(View v) {
            try {
                Socket clink = new Socket("10.10.104.57", 1000);
                PrintStream out = new PrintStream(clink.getOutputStream());
                BufferedReader in = new BufferedReader(new InputStreamReader(clink.getInputStream()));
                out.println("發送信息給ServerSocket");
                ActivityMain.this.textView.setText(in.readLine());

                in.close();
                out.close();
                clink.close();
            } catch (Exception e) {
            }
        }
    }
}

第三步:加上網路權限

別忘了在 AndroidManifest.xml 註冊 INTERNET 權限,否則程式會無法連線:

<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.android.main"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".ActivityMain"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

完成以上三步,點擊按鈕即可讓手機把訊息送到電腦,並把伺服器的回覆顯示在 TextView 上。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved