Connecting Devices Using Client and Server Architecture in Android: Part 1

Introduction

People always feel happy in sharing in any form. I have seen people's face when they share something, not in the case of Information Technology but in the real world as well. People always feel happy in sharing the magical moments of life in the form of the pictures and some other forms.

Let us consider the sharing of the data by two friends using Android devices. These friends will care only about the data, not with the mechanism of the Bluetooth technology but when in the case of development these things become important, let us see how.

Now the sharing of the data is done using Bluetooth and many other technologies in Android-enabled devices. What will we do in those cases?

We must make one the client and another the server because we are following the client and sever architecture. We are very well familiar with the traditional client and server architecture in which one is the server and another is the client. Using a MAC address of the devices we can do the communication.

Connecting as a server

When connecting two devices one must be the server by holding an open BluetoothServerSocket. First the data will be written on the socket and thus maintain the communication. When the BluetoothSocket is acquired from the BluetoothServerSocket, the BluetoothServerSocket can be discarded, unless you want to accept more connections.

Step 1

First get a BluetoothServerSocket by calling the method listenUsingRfcommWithServiceRecord(String, UUID). String is an identifiable name of your service that the system will automatically write a protocol that is the Service discovery Protocol database entry on the device.

Step 2

Start listening for connection requests by calling accept(). This is a blocking call, it depends on the user whether he want to accept or reject. It will return when either a connection has been accepted or an exception has occurred indicating the user has rejected the request. A connection is accepted only when a remote device has sent a connection request with a UUID matching the one registered with this listening server socket. When successful, accept() will return a connected BluetoothSocket.

Step 3

Calling the close() method.

The method releases the server socket and all its resources because the connection must be closed since otherwise it continues to consume, but does not close the connected BluetoothSocket that's been returned by accept(). Unlike TCP/IP, RFCOMM only allows one connected client per channel at a time, so in most cases it makes sense to call close() on the BluetoothServerSocket immediately after accepting a connected socket.

When the call is blocked in these cases we must write a code to abort a blocked call such as accept(), call close() on the BluetoothServerSocket from another thread and the blocked call will immediately return.

Note: All methods on a BluetoothServerSocket or BluetoothSocket must be thread-safe.

Code:

  1.    
  2. private class AcceptThread extends Thread {  
  3.     private final BluetoothServerSocket mmServerSocket;  
  4.    
  5.     public AcceptThread() {  
  6.         // Use a temporary object that is later assigned to mmServerSocket,  
  7.         // because mmServerSocket is final  
  8.         BluetoothServerSocket tmp = null;  
  9.         try {  
  10.             // MY_UUID is the app's UUID string, also used by the client code  
  11.             tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);  
  12.         } catch (IOException e) { }  
  13.         mmServerSocket = tmp;  
  14.     }  
  15.    
  16.     public void run() {  
  17.         BluetoothSocket socket = null;  
  18.         // Keep listening until exception occurs or a socket is returned  
  19.         while (true) {  
  20.             try {  
  21.                 socket = mmServerSocket.accept();  
  22.             } catch (IOException e) {  
  23.                 break;  
  24.             }  
  25.             // If a connection was accepted  
  26.             if (socket != null) {  
  27.                 // Do work to manage the connection (in a separate thread)  
  28.                 manageConnectedSocket(socket);  
  29.                 mmServerSocket.close();  
  30.                 break;  
  31.             }  
  32.         }  
  33.     }  
  34.    
  35.     /** Will cancel the listening socket, and cause the thread to finish */  
  36.     public void cancel() {  
  37.         try {  
  38.             mmServerSocket.close();  
  39.         } catch (IOException e) { }  
  40.     }  
  41. }  
Connecting as a Client

After executing as a server then it must be able to accept and send data as well. The client must acquire a BluetoothSocket and initiate the connection. 

Step 1

Using the BluetoothDevice, get a BluetoothSocket by calling createRfcommSocketToServiceRecord(UUID).

Step 2

Initiate the connection by calling connect().

Code:

  1. private class ConnectThread extends Thread {  
  2.     private final BluetoothSocket mmSocket;  
  3.     private final BluetoothDevice mmDevice;  
  4.    
  5.     public ConnectThread(BluetoothDevice device) {  
  6.         // Use a temporary object that is later assigned to mmSocket,  
  7.         // because mmSocket is final  
  8.         BluetoothSocket tmp = null;  
  9.         mmDevice = device;  
  10.    
  11.         // Get a BluetoothSocket to connect with the given BluetoothDevice  
  12.         try {  
  13.             // MY_UUID is the app's UUID string, also used by the server code  
  14.             tmp = device.createRfcommSocketToServiceRecord(MY_UUID);  
  15.         } catch (IOException e) { }  
  16.         mmSocket = tmp;  
  17.     }  
  18.    
  19.     public void run() {  
  20.         // Cancel discovery because it will slow down the connection  
  21.         mBluetoothAdapter.cancelDiscovery();  
  22.    
  23.         try {  
  24.             // Connect the device through the socket. This will block  
  25.             // until it succeeds or throws an exception  
  26.             mmSocket.connect();  
  27.         } catch (IOException connectException) {  
  28.             // Unable to connect; close the socket and get out  
  29.             try {  
  30.                 mmSocket.close();  
  31.             } catch (IOException closeException) { }  
  32.             return;  
  33.         }  
  34.    
  35.         // Do work to manage the connection (in a separate thread)  
  36.         manageConnectedSocket(mmSocket);  
  37.     }  
  38.    
  39.     /** Will cancel an in-progress connection, and close the socket */  
  40.     public void cancel() {  
  41.         try {  
  42.             mmSocket.close();  
  43.         } catch (IOException e) { }  
  44.     }  
  45. }  
Summary

This article illustrated how the sharing mechanism works using Bluetooth. Although we have only provided the basics of the Bluetooth technology as we make a client and server architecture. 

Up Next
    Ebook Download
    View all
    Learn
    View all