This project has moved. For the latest updates, please go here.

Bluetooth Server-side

The BluetoothListener class provides for RFCOMM server-side connections.

Bluetooth applications/services are identified and registered by UUID (Universally Unique Id), a 128-bit value that is represented by the System.Guid class in .NET. If one is creating a new service then a new UUID should be created at design time and entered into the two applications’ source code, a new value can be created either by calling Guid.NewValue or using the guidgen.exe Windows SDK program — in Visual Studio access it with menu item Tools, “Create GUID”.
One would thus use code like the following.

Class MyConsts
  Shared ReadOnly MyServiceUuid As Guid _
    = New Guid("{00112233-4455-6677-8899-aabbccddeeff}")
End Class

  Dim serviceClass As Guid
  serviceClass = BluetoothService.SerialPort
  ' - or - etc
  ' serviceClass = MyConsts.MyServiceUuid
  Dim lsnr As New BluetoothListener(serviceClass)

  ' Now accept new connections, perhaps using the thread pool to handle each
  Dim conn As New BluetoothClient = lsnr.AcceptBluetoothClient()
  Dim peerStream As Stream = conn.GetStream()

  ' etc
  conn As New BluetoothClient = lsnr.AcceptBluetoothClient()
  peerStream As Stream = conn.GetStream()
class MyConsts
    static readonly Guid MyServiceUuid
      = new Guid("{00112233-4455-6677-8899-aabbccddeeff}");

    Guid serviceClass;
    serviceClass = BluetoothService.SerialPort;
    // - or - etc
    // serviceClass = MyConsts.MyServiceUuid
    var lsnr = new BluetoothListener(serviceClass);

    // Now accept new connections, perhaps using the thread pool to handle each
    BluetoothClient conn = lsnr.AcceptBluetoothClient();
    Stream peerStream = conn.GetStream();

    // etc
    conn = lsnr.AcceptBluetoothClient();
    peerStream = conn.GetStream();

One can also pass the BluetoothListener a Service Name (v2.4), or a custom Service Record (Service Discovery Protocol record), and/or set Class of Service bit(s). To create a custom Service Record use ServiceRecordBuilder, see the SDP sections in the index and Creating Records.

Note that unlike with TCP/IP and IrDA, if another server is already listening on a given UUID, then no error occurs, but the first running server will likely receive all connections — though which is chosen is somewhat arbitrary depending in part how the client device uses SDP.

Note: in particular Broadcom/Widcomm runs a COM port by default and thus will grab all incoming connections to the SerialPort service. To receive connections by BluetoothListener there either use a new unique Service Class Id as described above, or disable the Widcomm COM port somehow...

Last edited Dec 29, 2012 at 8:54 PM by alanjmcf, version 6