"A socket operation failed because the destination host was down" 将电脑连接到移动设备时

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

我的项目是使用 32feet.net 库连接电脑和移动设备。

到目前为止,我的解决方案是执行以下步骤:

  1. 正在扫描区域中的设备。

  2. 正在与所选设备配对。

  3. 请求与移动设备配对,当没问题时出现此错误:

"A socket operation failed because the destination host was down" 而且我不知道为什么以及如何克服这个问题。任何对此问题的帮助将不胜感激。

我的解决方案是:

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

我想我跟你做了同样的例子,当然我遇到了同样的问题。

在 "private void ClientconnectThread()" 功能之前,我的其余代码与您的相同,这是我的代码;

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);
            }
        }
    }

使用此代码,我可以连接远程设备并实现基本的 send/receive 数据通信。为了我在互联网上的搜索,"if this code does not fit for you",你可能会认为 32feet 与你的蓝牙驱动程序不兼容。 (顺便说一句,我的电脑 OS 是 64 位 Win7,我使用我电脑的内置 BT 设备)

此致。