Blog -
前回は、設計に際しての概要まで纏めましたが 今回はちょっと具体的に
【サーバとしての接続】
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 チュートリアルを使用しています。