Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android Socket 通信開發完整實例(含伺服器端)

編輯:Android 開發實例

Android 用戶端要透過 Socket 與伺服器通信,可以拆成幾個固定步驟。而在選擇之前,你得先決定要用哪種傳輸模式:TCP 提供可靠、有連線導向的通信;UDP 則是無連線、不保證送達但負擔更輕。

用戶端的四個步驟

(1)以 IP 與埠號建立 Socket,發起連線。

socket = new Socket(HOST, PORT); // HOST 為伺服器 IP,PORT 為伺服器埠號

(2)取得 Socket 串流進行讀寫,並包裝成好用的高階 Writer。

PrintWriter out = new PrintWriter(
        new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

這一行涉及三層包裝:socket.getOutputStream() 取得位元組輸出串流;OutputStreamWriter 是位元組轉字元的橋梁;BufferedWriter 加上緩衝;最後包進 PrintWriter,就能直接用 println() 寫資料。

(3)進行讀寫。

if (socket.isConnected()) {
    if (!socket.isOutputShutdown()) {
        out.println(msg);
    }
}

(4)關閉串流。

out.close();

寫 Socket 程式時,務必注意輸入串流與輸出串流的關閉。這不是形式上的規矩:串流未關閉會導致連線無法正常釋放,長時間運行下來會耗盡系統資源。

版面配置

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:id="@+id/TextView"
        android:singleLine="false"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <EditText
        android:hint="content"
        android:id="@+id/EditText01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
    </EditText>

    <Button
        android:text="send"
        android:id="@+id/Button02"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
    </Button>
</LinearLayout>

Android 用戶端程式碼

package com.android.SocketDemo;

public class SocketDemo extends Activity implements Runnable {
    private TextView tv_msg = null;
    private EditText ed_msg = null;
    private Button btn_send = null;
    private static final String HOST = "192.168.1.223";
    private static final int PORT = 9999;
    private Socket socket = null;
    private BufferedReader in = null;
    private PrintWriter out = null;
    private String content = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        tv_msg = (TextView) findViewById(R.id.TextView);
        ed_msg = (EditText) findViewById(R.id.EditText01);
        btn_send = (Button) findViewById(R.id.Button02);

        try {
            socket = new Socket(HOST, PORT);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())), true);
        } catch (IOException ex) {
            ex.printStackTrace();
            ShowDialog("連線失敗:" + ex.getMessage());
        }

        btn_send.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                String msg = ed_msg.getText().toString();
                if (socket.isConnected()) {
                    if (!socket.isOutputShutdown()) {
                        out.println(msg);
                    }
                }
            }
        });

        new Thread(SocketDemo.this).start();
    }

    public void ShowDialog(String msg) {
        new AlertDialog.Builder(this).setTitle("通知").setMessage(msg)
                .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) { }
                }).show();
    }

    public void run() {
        try {
            while (true) {
                if (socket.isConnected()) {
                    if (!socket.isInputShutdown()) {
                        if ((content = in.readLine()) != null) {
                            content += "\n";
                            mHandler.sendMessage(mHandler.obtainMessage());
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            tv_msg.setText(tv_msg.getText().toString() + content);
        }
    };
}

伺服器端程式碼

public class Main {
    private static final int PORT = 9999;
    private List<Socket> mList = new ArrayList<Socket>();
    private ServerSocket server = null;
    private ExecutorService mExecutorService = null; // 執行緒池

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        try {
            server = new ServerSocket(PORT);
            mExecutorService = Executors.newCachedThreadPool();
            System.out.print("server start ...");
            Socket client = null;
            while (true) {
                client = server.accept();
                mList.add(client);
                // 每個連線交給一個執行緒處理
                mExecutorService.execute(new Service(client));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class Service implements Runnable {
        private Socket socket;
        private BufferedReader in = null;
        private String msg = "";

        public Service(Socket socket) {
            this.socket = socket;
            try {
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                msg = "user" + this.socket.getInetAddress() + " 上線,目前人數:" + mList.size();
                this.sendmsg();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            try {
                while (true) {
                    if ((msg = in.readLine()) != null) {
                        if (msg.equals("exit")) {
                            mList.remove(socket);
                            in.close();
                            msg = "user:" + socket.getInetAddress()
                                    + " 離線,剩餘人數:" + mList.size();
                            socket.close();
                            this.sendmsg();
                            break;
                        } else {
                            msg = socket.getInetAddress() + ":" + msg;
                            this.sendmsg();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 群播給所有已連線的用戶端
        public void sendmsg() {
            System.out.println(msg);
            int num = mList.size();
            for (int index = 0; index < num; index++) {
                Socket mSocket = mList.get(index);
                PrintWriter pout = null;
                try {
                    pout = new PrintWriter(new BufferedWriter(
                            new OutputStreamWriter(mSocket.getOutputStream())), true);
                    pout.println(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

別忘了權限

最後,記得在 AndroidManifest.xml 中加上網路存取權限,否則連線會直接被系統攔下:

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

幾個實務上的提醒

這個範例足以說明 Socket 通信的骨架,但直接搬進正式專案前,有幾點值得留意。

網路操作絕不能放在主執行緒。範例中已用獨立 Thread 承載讀取迴圈,這點務必保留;Android 4.0 之後,主執行緒上的網路請求會直接拋出 NetworkOnMainThreadException。

讀取迴圈是阻塞的。in.readLine() 會一直卡在那裡等待資料,因此它必須跑在自己的執行緒上,而且結束時要有明確的收尾機制,避免執行緒洩漏。

sendmsg() 每次都重新建立串流,效率不佳。正式環境中應在連線建立時就快取每個 client 對應的 PrintWriter,並在移除連線時一併關閉。

這個範例沒有處理斷線重連。行動網路環境下連線中斷是常態而非例外,加上心跳機制與自動重連,才能做出可用的即時通訊功能。

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