JSR-82 Sample : SPP Server and Client

This article will teach you how to develop bluetooth server and client application and communicate each other using it. We will learn how to develop an SPP Server and an SPP client using JSR 82 API.


SPP Server

Any Java Bluetooth service initialization consists of the following steps

  • Constructing the connection URL.
  • The connection URL consists of the protocol identifier, the UUID of the the service, and other optional attributes. Since we are creating an SPP service, the protocol identifier will be "btspp". The UUID for the SPP service is defined to be 1101. This step is realized by the following code

    1. //Create a UUID for SPP
    2. UUID uuid = new UUID("1101", true);
    3. //Create the servicve url
    4. String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server";

  • Registering service and Waiting for Client connection.
  • The next step is to register for the service and to wait for client connection. This step is achieved by the following codes

    1. //open server url
    2. StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );
    3. //Wait for client connection
    4. StreamConnection connection=streamConnNotifier.acceptAndOpen ();

    The acceptAndOpen method waits until a client is connected.

  • Communicate with the client
  • Once a client is connected, use the returned 'Connection' object to open the input and output streams with the client. Now we have a stream connection with a remote bluetooth device, that can be used to develop your application.

SPP Client

Writing a client in JSR 82 is very easy. It consists of the following steps

  • Finding the connection URL to the service.
  • If you already knew the direct url to the server, this step can be skipped. This consist of searching for a service, and getting its connection URL. More details about this can be learned from the article about bluetooth service search

  • Connect to server
  • Once we know the connection url, simply connect with the server using the "Connector.open" and open the input/output streams from the created 'Connection' object. The rest is up to your logic to build your applpication based on this connection

    The complete code for a simple SPP Server that accepts an SPP connection and reads a single line and writes a single line back is given below. The source code for an SPP client that connects with the server and sends a single line is also given. For this sample to work, you need a JSR-82 Implmentation (Java Bluetooth Stack) like ElectricBlue in the class path

SPP Server Source Code

  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.InputStreamReader;
  5. import java.io.OutputStream;
  6. import java.io.OutputStreamWriter;
  7. import java.io.PrintWriter;
  8.  
  9. import javax.bluetooth.*;
  10. import javax.microedition.io.*;
  11.  
  12. /**
  13. * Class that implements an SPP Server which accepts single line of
  14. * message from an SPP client and sends a single line of response to the client.
  15. */
  16. public class SampleSPPServer {
  17.    
  18.     //start server
  19.     private void startServer() throws IOException{
  20.  
  21.         //Create a UUID for SPP
  22.         UUID uuid = new UUID("1101", true);
  23.         //Create the servicve url
  24.         String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server";
  25.        
  26.         //open server url
  27.         StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );
  28.        
  29.         //Wait for client connection
  30.         System.out.println("\nServer Started. Waiting for clients to connect...");
  31.         StreamConnection connection=streamConnNotifier.acceptAndOpen();
  32.  
  33.         RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
  34.         System.out.println("Remote device address: "+dev.getBluetoothAddress());
  35.         System.out.println("Remote device name: "+dev.getFriendlyName(true));
  36.        
  37.         //read string from spp client
  38.         InputStream inStream=connection.openInputStream();
  39.         BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
  40.         String lineRead=bReader.readLine();
  41.         System.out.println(lineRead);
  42.        
  43.         //send response to spp client
  44.         OutputStream outStream=connection.openOutputStream();
  45.         PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
  46.         pWriter.write("Response String from SPP Server\r\n");
  47.         pWriter.flush();
  48.  
  49.         pWriter.close();
  50.         streamConnNotifier.close();
  51.  
  52.     }
  53.  
  54.  
  55.     public static void main(String[] args) throws IOException {
  56.        
  57.         //display local device address and name
  58.         LocalDevice localDevice = LocalDevice.getLocalDevice();
  59.         System.out.println("Address: "+localDevice.getBluetoothAddress());
  60.         System.out.println("Name: "+localDevice.getFriendlyName());
  61.        
  62.         SampleSPPServer sampleSPPServer=new SampleSPPServer();
  63.         sampleSPPServer.startServer();
  64.        
  65.     }
  66. }

SPP Client Source Code

  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.InputStreamReader;
  5. import java.io.OutputStream;
  6. import java.io.OutputStreamWriter;
  7. import java.io.PrintWriter;
  8. import java.util.Vector;
  9.  
  10. import javax.bluetooth.DeviceClass;
  11. import javax.bluetooth.DiscoveryAgent;
  12. import javax.bluetooth.DiscoveryListener;
  13. import javax.bluetooth.LocalDevice;
  14. import javax.bluetooth.RemoteDevice;
  15. import javax.bluetooth.ServiceRecord;
  16. import javax.bluetooth.UUID;
  17. import javax.microedition.io.Connector;
  18. import javax.microedition.io.StreamConnection;
  19.  
  20. /**
  21. * A simple SPP client that connects with an SPP server
  22. */
  23. public class SampleSPPClient implements DiscoveryListener{
  24.    
  25.     //object used for waiting
  26.     private static Object lock=new Object();
  27.    
  28.     //vector containing the devices discovered
  29.     private static Vector vecDevices=new Vector();
  30.    
  31.     private static String connectionURL=null;
  32.  
  33.     public static void main(String[] args) throws IOException {
  34.        
  35.         SampleSPPClient client=new SampleSPPClient();
  36.        
  37.         //display local device address and name
  38.         LocalDevice localDevice = LocalDevice.getLocalDevice();
  39.         System.out.println("Address: "+localDevice.getBluetoothAddress());
  40.         System.out.println("Name: "+localDevice.getFriendlyName());
  41.        
  42.         //find devices
  43.         DiscoveryAgent agent = localDevice.getDiscoveryAgent();
  44.       
  45.         System.out.println("Starting device inquiry...");
  46.         agent.startInquiry(DiscoveryAgent.GIAC, client);
  47.        
  48.         try {
  49.             synchronized(lock){
  50.                 lock.wait();
  51.             }
  52.         }
  53.         catch (InterruptedException e) {
  54.             e.printStackTrace();
  55.         }
  56.        
  57.        
  58.         System.out.println("Device Inquiry Completed. ");
  59.        
  60.         //print all devices in vecDevices
  61.         int deviceCount=vecDevices.size();
  62.        
  63.         if(deviceCount <= 0){
  64.             System.out.println("No Devices Found .");
  65.             System.exit(0);
  66.         }
  67.         else{
  68.             //print bluetooth device addresses and names in the format [ No. address (name) ]
  69.             System.out.println("Bluetooth Devices: ");
  70.             for (int i = 0; i <deviceCount; i++) {
  71.                 RemoteDevice remoteDevice=(RemoteDevice)vecDevices.elementAt(i);
  72.                 System.out.println((i+1)+". "+remoteDevice.getBluetoothAddress()+" ("+remoteDevice.getFriendlyName(true)+")");
  73.             }
  74.         }
  75.        
  76.         System.out.print("Choose Device index: ");
  77.         BufferedReader bReader=new BufferedReader(new InputStreamReader(System.in));
  78.        
  79.         String chosenIndex=bReader.readLine();
  80.         int index=Integer.parseInt(chosenIndex.trim());
  81.        
  82.         //check for spp service
  83.         RemoteDevice remoteDevice=(RemoteDevice)vecDevices.elementAt(index-1);
  84.         UUID[] uuidSet = new UUID[1];
  85.         uuidSet[0]=new UUID("1101",false);
  86.        
  87.         System.out.println("\nSearching for service...");
  88.         agent.searchServices(null,uuidSet,remoteDevice,client);
  89.        
  90.         try {
  91.             synchronized(lock){
  92.                 lock.wait();
  93.             }
  94.         }
  95.         catch (InterruptedException e) {
  96.             e.printStackTrace();
  97.         }
  98.        
  99.         if(connectionURL==null){
  100.             System.out.println("Device does not support Simple SPP Service.");
  101.             System.exit(0);
  102.         }
  103.        
  104.         //connect to the server and send a line of text
  105.         StreamConnection streamConnection=(StreamConnection)Connector.open(connectionURL);
  106.        
  107.         //send string
  108.         OutputStream outStream=streamConnection.openOutputStream();
  109.         PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
  110.         pWriter.write("Test String from SPP Client\r\n");
  111.         pWriter.flush();
  112.        
  113.        
  114.         //read response
  115.         InputStream inStream=streamConnection.openInputStream();
  116.         BufferedReader bReader2=new BufferedReader(new InputStreamReader(inStream));
  117.         String lineRead=bReader2.readLine();
  118.         System.out.println(lineRead);
  119.        
  120.                
  121.     }//main
  122.    
  123.     //methods of DiscoveryListener
  124.     public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
  125.         //add the device to the vector
  126.         if(!vecDevices.contains(btDevice)){
  127.             vecDevices.addElement(btDevice);
  128.         }
  129.     }
  130.  
  131.     //implement this method since services are not being discovered
  132.     public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
  133.         if(servRecord!=null && servRecord.length>0){
  134.             connectionURL=servRecord[0].getConnectionURL(0,false);
  135.         }
  136.         synchronized(lock){
  137.             lock.notify();
  138.         }
  139.     }
  140.  
  141.     //implement this method since services are not being discovered
  142.     public void serviceSearchCompleted(int transID, int respCode) {
  143.         synchronized(lock){
  144.             lock.notify();
  145.         }
  146.     }
  147.  
  148.    
  149.     public void inquiryCompleted(int discType) {
  150.         synchronized(lock){
  151.             lock.notify();
  152.         }
  153.        
  154.     }//end method
  155.    
  156.    
  157.    
  158. }

AddThis Social Bookmark Button AddThis Feed Button

3 Responses to “JSR-82 Sample : SPP Server and Client”

  1. BooH Says:

    I tryied it on netbeans, it says it cannot find BufferedReader and PrintWriter....
    =(
    Do I have to add any library or jar file??
    =D
    Tanks

  2. Bruse Says:

    Yes, the sample shows a JavaSE code as an example. Just remove/replace those codes that reads the input from the user (PrintWriter/BufferedReader), and the code will work with J2ME

  3. Lee Says:

    I got an exception when I run the code of server, Exception Occured:javax.bluetooth.BluetoothStateException
    It seems that it does not find the bluetooth device on my laptop, what kind of this problem? Actually My laptop is built with bluetooth chip.

Leave a Comment