Blog -

カテゴリ : 
Android » Tips
執筆 : 
NickQ 2011-8-11 15:14

前回は、設計に際しての概要まで纏めましたが 今回はちょっと具体的に

【サーバとしての接続】

 

private class AcceptThread extends Thread { 
	private final BluetoothServerSocket mmServerSocket;
	//中略
}

 

AcceptThreadというThreadを作って、そのコンストラクタで

 

    public AcceptThread() {
        // Use a temporary object that is later assigned to mmServerSocket,
        // because mmServerSocket is final
        BluetoothServerSocket tmp = null;
        try {
            // MY_UUID is the app's UUID string, also used by the client code
            tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
        } catch (IOException e) { }
        mmServerSocket = tmp;
    }

 

BluetoothServerSocketをの有無を確認して無ければ(無いというのは、接続中か接続後か)

BluetoothServerSocketを用意する、Threadなのでrun()メソッドが開始される。

 

    public void run() {
        BluetoothSocket socket = null;
        // Keep listening until exception occurs or a socket is returned
        while (true) {
            try {
                socket = mmServerSocket.accept();
            } catch (IOException e) {
                break;
            }
            // If a connection was accepted
            if (socket != null) {
                // Do work to manage the connection (in a separate thread)
                manageConnectedSocket(socket);
                mmServerSocket.close();
                break;
            }
        }
    }

 

run()の中では、BluetoothSocketを初期化してaccept()を発行しリスニングを開始します。

クライアントがBluetoothSocketを要求するとBluetoothSocketがsocketへソケットを用意します。

socket(接続以降)の処理を開始して、BluetoothSocketをclose()して終了します。 また、処理を中断した時の処理も記述します。

 

    public void cancel() {
        try {
            mmServerSocket.close();
        } catch (IOException e) { }
    }

 

これで、サーバソケットでの待機が理解出来ました。

注意点として、accept() が BluetoothSocket を返すときは、ソケットがすでに接続済みでなので

connect() メソッドを呼び出す必要はありません ( クライアントサイドでしている想定 )

 

※GoogleDevelopers チュートリアルを使用しています。

  • コメント (0)
  • トラックバック (0)
  • 閲覧 (10170)

トラックバック

トラックバックpingアドレス http://three-thread.sakura.ne.jp/tt/modules/d3blog/tb.php/26

コメントの投稿

コメント投稿に関するルール : 登録ユーザ以外のコメントは承認が必要
最新のコメント
  • NickQ(2012/11/19)
  • ゲスト(2012/11/19)
最新のトラックバック
メインメニュー

ログイン
ユーザー名:

パスワード:


SSL パスワード紛失


カテゴリ一覧

アーカイブ

Books