Search code examples
c#socketsnetwork-programmingbluetooth32feet

"A socket operation failed because the destination host was down" when connecting pc to mobie device


My project is to connecting pc with mobile device using 32feet.net library.

Until Now, my solution is doing steps like:

  1. Scanning for devices in area.

  2. pairing with selected device .

  3. request pairing with mobile device and when it's okay this error appear :

"A socket operation failed because the destination host was down" and I don't know why and how to overcome this problem. Any help with this problem will be appreciated.

And my solution is:

namespace Bluetooth
{

public partial class Form1 : Form
{
    List<string> items;
    public Form1()
    {
        items = new List<string>();

        InitializeComponent();
    }

    private void Connect_Click(object sender, EventArgs e)
    {
        if(ServerStarted )
        {
            updateUI("Server Already Started");
            return;
        }
        if(rbClient.Checked)
        {
            //ConnectAsClient();
            StartScan();
        }
        else
        {
            ConnectAsServer();
        }
    }
    private void StartScan()
    {
        listBox.DataSource = null;
        listBox.Items.Clear();
        items.Clear();
        Thread bluethoothscanthread = new Thread(new ThreadStart(scan));
        bluethoothscanthread.Start();
    }
    BluetoothDeviceInfo[] devices;
    private void scan()
    {
        updateUI("Starting Scan ...");
        BluetoothClient client = new BluetoothClient();
        devices = client.DiscoverDevicesInRange();
        updateUI("Scan Completed......");
        updateUI(devices.Length.ToString() + "devices discovered");
        foreach(BluetoothDeviceInfo d in devices)
        {
            items.Add(d.DeviceName);
        }

        UpdateDeviceList();
    }

    private void ConnectAsServer()
    {
        Thread BluethoothServerThread = new Thread(new ThreadStart(ServerConnectThread));
        BluethoothServerThread.Start();
    }

    private void ConnectAsClient()
    {
        throw new NotImplementedException();
    }

    Guid mUUID = new Guid("00001101-0000-1000-8000-00805F9B34FB");  

    bool ServerStarted = false;
    public void ServerConnectThread()
    {
        ServerStarted = true;
        updateUI("Server Started , Waiting For Clients ");
       BluetoothListener bluelistner = new BluetoothListener(mUUID);
       bluelistner.Start();
       BluetoothClient conn = bluelistner.AcceptBluetoothClient();
       updateUI("Client has connected");
       Stream mstream = conn.GetStream();

        while(true)
        {
            // handle server connection
            try
            {
                byte[] Received = new byte[1024];
                mstream.Read(Received, 0, Received.Length);
                updateUI("Received : " + Encoding.ASCII.GetString(Received));
                byte[] Sent = Encoding.ASCII.GetBytes("Hello World ");
                mstream.Write(Sent, 0, Sent.Length);
            }
            catch(IOException exception)
            {
                updateUI("Client has disconnected !!! ");
            }
        }
    }
    private void updateUI(string message)
    {
        Func<int> del = delegate ()
            {
                tbOutput.AppendText(message + System.Environment.NewLine);
                return 0 ;
            };
            Invoke(del);       
    }

    private void UpdateDeviceList()
    {
        Func<int> del = delegate ()
        {
            listBox.DataSource = items;
            return 0;
        };
        Invoke(del);
    }

    BluetoothDeviceInfo deviceinfo;
    private void listBox_DoubleClick(object sender, EventArgs e)
    {
        deviceinfo = devices.ElementAt(listBox.SelectedIndex);
        updateUI(deviceinfo.DeviceName + "Was Selected , attempting connect");
       if( pairDevice())
       {
           updateUI("Device Paired.....");
           updateUI("Starting Connect Thread");
           Thread bluethoothClientThread = new Thread(new ThreadStart(ClientconnectThread));
           bluethoothClientThread.Start();
       }
       else
       {
           updateUI("Pair Failed");
       }
    }

    private void ClientconnectThread()
    {
        BluetoothClient client = new BluetoothClient();
        updateUI("Attempting Connect");
        client.BeginConnect(deviceinfo.DeviceAddress, mUUID, this.BluetoothClientConnectCallback, client);
    }
    void BluetoothClientConnectCallback(IAsyncResult result)
    {
        BluetoothClient client = (BluetoothClient)result.AsyncState;

       BluetoothEndPoint bep = new BluetoothEndPoint(deviceinfo.DeviceAddress, BluetoothService.AvctpProtocol);
       BluetoothClient cli = new BluetoothClient();

       client.Connect(bep); // the exception throw in this line //
       Stream stream = cli.GetStream();
       stream.ReadTimeout = 10000;
       //Stream peerStream = cli.GetStream();

        // client.Connect(BluetoothAddress.Parse(items(0)), mUUID);


        //client.EndConnect(result);
        //while(true)
        //{
        //    while (!ready) ;
        //    stream.Write(message, 0, message.Length);
        //}

        //streaming(result);
        if(result.IsCompleted)
        {
           // client.EndConnect(result);
           // Stream stream = client.GetStream();
           // stream.ReadTimeout = 1000;

            updateUI("Ya rabbbbb");


            //while (!ready) ;
            //stream.Write(message, 0, message.Length);
        }
    }
    void streaming (IAsyncResult result)
    {
        BluetoothListener listn = new BluetoothListener(mUUID);
        listn.Start();
        BluetoothClient conn = listn.AcceptBluetoothClient();
        Stream peerstream = conn.GetStream();
        bool rightconn = peerstream.CanRead;
        if(rightconn)
        {
            updateUI("Now you can streaming");
        }
        else
        {
            updateUI("Not Yet");
        }
    }

    string mypin = "1234";
    private bool pairDevice()
    {
        if(!deviceinfo.Authenticated)
        {
            if (!BluetoothSecurity.PairRequest(deviceinfo.DeviceAddress, mypin))
            {
                return false;
            }
        }
        return true;
    }

    bool ready = false;
    byte[] message;
    private void tbText_KeyPress(object sender, KeyPressEventArgs e)
    {
        if(e.KeyChar == 13)
        {
            message = Encoding.ASCII.GetBytes(tbText.Text);
            ready = true;
            tbText.Clear();
        }
    }
}

} // End of namespace

Solution

  • I think I followed same example with you and of course I encountered same problem.

    Rest of my codes are same with yours until "private void ClientconnectThread()" function and here is mine;

    private void ClientConnectThread()
        {
            BluetoothClient client = new BluetoothClient();
            updateUI("attempting connect");
            //client.BeginConnect(deviceInfo.DeviceAddress, mUUID, this.BluetoothClientConnectCallback, client);
            BluetoothAddress addressSeleccionado = deviceInfo.DeviceAddress;
            Guid mUUID = new Guid("00001101-0000-1000-8000-00805F9B34FB");
            BluetoothEndPoint ep = new BluetoothEndPoint(addressSeleccionado, mUUID);
            client.Connect(ep);
            updateUI("connected");
            Stream stream = client.GetStream();
            while (true)
            {
                byte[] received = new byte[1024];
                stream.Read(received, 0, received.Length);
                updateUI("received: ");
                for (int i = 0; i < 15; i++)
                {
                    updateUI(received[i].ToString());
                }
                if (ready)
                {
                    ready = false;
                    stream.Write(message, 0, message.Length);
                }
            }
        }
    

    With this code I can connect the remote device and implement basic send/receive data communication. In order to my search over internet, "if this code does not fit for you", you might think that 32feet is not compatible with your bluetooth driver. (by the way my PC's OS is 64bit Win7 and I use the internal BT device of my PC )

    Best regards.