Samsung Electronics logo

Connecting to and Exchanging Data with a Bluetooth Device

The Radio Frequency Communication (RFCOMM) is a set of transport protocols which allows multiple simultaneous connections to a device. This protocol enables you to convert your Bluetooth device to an Internet modem, for example, for a multiplayer game. The device that provides a service is called a server device, and devices that request the service are called client devices.

Learning how to connect to services provided by a server device to the client devices is a basic Bluetooth management skill:

  1. Retrieve a BluetoothAdapter object instance with the getDefaultAdapter() method:

    var adapter = webapis.bluetooth.getDefaultAdapter();
  2. To register a service and allow client devices to connect to it, use the registerRFCOMMServiceByUUID() method on the server device:

    adapter.registerRFCOMMServiceByUUID(serviceUUID, "My service", 
                                        registerSuccessCallback, onError);
    For P2P communication between 2 instances of the same application, the UUID can be hard-coded in your application. To retrieve the UUID of an unknown Bluetooth device, such as a Bluetooth-enabled sensor or a microphone, use the BluetoothDevice object. The object has an array of UUIDs available for the device.

    When the service has been successfully registered, the onsuccess event handler in the BluetoothServiceSuccessCallback interface is triggered.

  3. To connect to the server device, use the connectToServiceByUUID() method on the client device:

    device.connectToServiceByUUID(serviceUUID, onSocketConnected, 

    When a connection between 2 devices is established, the onsuccess event handler in the BluetoothSocketSuccessCallback interface on the client device and the onconnect event handler in the BluetoothServiceHandler interface on the server device are triggered.

  4. To send data to the peer device, use the writeData() method:

    var length = socket.writeData(sendtextmsg);

    To send data between the devices, a socket mechanism with the BluetoothSocket interface must be used. The proper socket is received when the devices are connected.

  5. To read the data in the server device, use the readData() method:

    var data = socket.readData();

    When an incoming message is received from the peer device, the onmessage event handler in the BluetoothSocket interface is triggered.