2015-03-02 1 views
1

Мой проект заключается в подключении компьютера к мобильному устройству с использованием библиотеки 32feet.net.«Операция сокета не удалась, потому что хост назначения был выключен» при подключении компьютера к мобильному устройству

До сих пор мое решение не делает шаги, как:

  1. Сканирование для устройств в области.

  2. сопряжение с выбранным устройством.

  3. запрос сопряжения с мобильным устройством, и когда это нормально появляется эта ошибка:

«Операция сокета не удалось, так как узел назначения был вниз», и я не знаю, почему и как решить эту проблему , Любая помощь с этой проблемой будет оценена по достоинству.

И мое решение:

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 
+0

, в котором строка кода точно не срабатывала? –

+0

@IanChuTe любое предложение ???! – user3903128

ответ

1

Я думаю, что я последовал за тот же пример с вами и, конечно, я столкнулся с той же проблемой.

Остальные мои коды те же, что и у вас, до тех пор, пока функция 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); 
      } 
     } 
    } 

С помощью этого кода я могу подключить удаленное устройство и осуществить базовую передачу данных. Для моего поиска через интернет, «если этот код не подходит для вас», вы можете подумать, что 32feet несовместим с вашим драйвером Bluetooth. (кстати, ОС моего компьютера - 64-битный Win7, и я использую внутреннее устройство BT моего ПК)

С уважением.

+0

Большое вам спасибо – user3903128

Смежные вопросы