Bluetooth SPP Server端

1 篇文章 / 0 new
author
Bluetooth SPP Server端
Server端啟動一個 SPP 服務, 讓遠端可以透過 SPP 進行數據交換
Thread bluetoothServerThread;
private void connectAsServer()
{
    bluetoothServerThread = new Thread(new ThreadStart(ServerConnectThread));
    bluetoothServerThread.Start();
}
//Create a UUID for SPP
//UUID uuid = new UUID("1101", true);
Guid mUUID = BluetoothService.SerialPort;
BluetoothListener blueListener;
private void ServerConnectThread()
{
    //SPP 開始服務, 等候連結
    blueListener = new BluetoothListener(mUUID);
    blueListener.ServiceName = "SPP-Port";
    blueListener.Start();
    byte[] received = new byte[1024];
    while (serverStart)
    {
        if (blueListener.Pending())
        {
            BluetoothClient conn = blueListener.AcceptBluetoothClient();
            serverClientConnectedState(conn.RemoteMachineName, true);
            Stream stream = conn.GetStream();
            stream.ReadTimeout = 1000;
            //conn.Connected 一經連線後均為 true, 不知何時會 false
            while (serverStart && conn.Connected)
            {
                try
                {
                    int l = stream.Read(received, 0, received.Length);
                    //怪怪邏輯, 當client有open port連入時, 沒讀到資料會丟出System.IOExpection
                    //但當client沒有open port時, 沒讀到資料則傳回0, 而不會拋出Exception
                    if (l > 0)
                    {
                        String d = Encoding.Unicode.GetString(received, 0, l);
                        updateUI(String.Format("[接收] {0}", d));
                        stream.Flush();
                        byte[] send = Encoding.Unicode.GetBytes(String.Format("<回應> {0}", d));
                        stream.Write(send, 0, send.Length);
                    }
                    else
                        break;
                }
                catch (Exception e) { }
                Thread.Sleep(100);
            }
            serverClientConnectedState(conn.RemoteMachineName, false);
            //階段服務結束
            stream.Close();
            conn.Close();
            conn.Dispose();
        }
        Thread.Sleep(100);
    }
    //SPP 終止服務
}
關鍵字: 
Free Web Hosting