2013-02-02 39 views
1

我想在C#中開發一個應用程序,它充當一個Android手機的服務器。我在C#中使用32feet.net進行藍牙,並且我有一臺運行在android上的服務器,將套接字發送到服務器。運行在PC上的服務器需要監聽連接並顯示連接狀態。所有這些都是我的項目的基礎。服務器代碼如下所示:c#服務器和Android客戶端,連接

namespace testserver 
{ 
class Program 
{ 

    static void Main(string[] args) 
    { 

     BluetoothClient bc = new BluetoothClient(); 
     BluetoothDeviceInfo[] dev; 
     BluetoothDeviceInfo td=null; 
     Guid id = new Guid("{00112233-4455-6677-8899-aabbccddeeff}"); 
     // Console.WriteLine(id.ToString()); 
     // Console.Read(); 
     dev = bc.DiscoverDevices(); 
     foreach (BluetoothDeviceInfo d in dev) 
     { 
      if (d.DeviceName == "ST21i")//my phone name 
      { 
       td=d; 
       break; 
      } 
     } 
     try 
     { 

      BluetoothAddress addr = td.DeviceAddress; 
      BluetoothListener bl = new BluetoothListener(addr, id); 
      bl.Start(); 
      if (bl.AcceptSocket() != null) 
       Console.WriteLine("Success"); 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine("Exception : "+e.Message); 
      Console.Read(); 
     } 


    } 
} 

}

,這裏是我的Android代碼:

public class MainActivity extends Activity { 


BluetoothAdapter adapter; 
    BluetoothDevice bd; 
BluetoothSocket sock; 
OutputStream ostr; 
int REQUEST_ENABLE_BT; 
String str="5C:AC:4C:DD:CC:0D"; 

private static final UUID id=UUID.fromString("00112233-4455-6677-8899-   aabbccddeeff"); 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.activity_main); 
    adapter=BluetoothAdapter.getDefaultAdapter(); 

    if (!adapter.isEnabled()) { 
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
     startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); 
    } 


    Button b = (Button) findViewById(R.id.button1); 
    b.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
Toast.makeText(getApplicationContext(), "clicked button",   Toast.LENGTH_LONG).show(); 
    try 
    { 
     bd=adapter.getRemoteDevice(str);      Toast.makeText(getApplicationContext(),"Server is running at "+bd.getName().toString()+"...", Toast.LENGTH_LONG).show(); 
        sock=bd.createInsecureRfcommSocketToServiceRecord(id);     sock.connect(); 
       ostr=sock.getOutputStream(); 
       ostr.write(0); 
      } 
      catch(Exception e) 
      { 
       Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_LONG).show(); 
      } 
     } 
    }); 

} 

}

我的問題是:在PC

1)我收到一個異常,請求的地址在其上下文中無效(這樣服務器無法運行) 2)在手機中,服務發現失敗(由於服務器不可用)

如何更正服務器並運行程序?

回答

1

我改變了藍牙監聽對象的創建從 BluetoothListener bl = new BluetoothListener(addr, id);BluetoothListener bl = new BluetoothListener(id);和一切工作很好..