Click here to Skip to main content
16,023,224 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
package bluetooth;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import javax.bluetooth.*;
import javax.microedition.io.*;

public class SampleSPPServer
{
  //start server

  private void startServer() throws IOException
  {
    //Create a UUID for SPP
    UUID uuid = new UUID("1101", true);
    //Create the servicve url
    String connectionString = "btspp://localhost:" +
        uuid +";name=Sample SPP Server";
    System.out.println(connectionString);
    //open server url
    StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );
    //Wait for client connection
    System.out.println("\nServer Started. Waiting for clients to connect...");
    StreamConnection connection=streamConnNotifier.acceptAndOpen();
    RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
    System.out.println("Remote device address: " + dev.getBluetoothAddress());
    System.out.println("Remote device name: " + dev.getFriendlyName(true));
    //read string from spp client
    InputStream inStream=connection.openInputStream();
    BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
    String lineRead=bReader.readLine();
    System.out.println(lineRead);

    //send response to spp client
    OutputStream outStream=connection.openOutputStream();
    PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
    pWriter.write("Response String from SPP Server\r\n");
    pWriter.flush();
    pWriter.close();
    streamConnNotifier.close();
  }

  public static void main(String[] args) throws IOException
  {
    //display local device address and nam
    LocalDevice localDevice = LocalDevice.getLocalDevice();
    System.out.println("Address: " + localDevice.getBluetoothAddress());
    System.out.println("Name: " + localDevice.getFriendlyName());
    SampleSPPServer sampleSPPServer=new SampleSPPServer();
    sampleSPPServer.startServer();
  }
}

........................................................................
Client:



package bluetooth;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Vector;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;

/**  21.
 * A simple SPP client that connects with an SPP server  22.
 */

public class SampleSPPClient implements DiscoveryListener
{
  //object used for waiting
  private static Object lock=new Object();
  //vector containing the devices discovered
  private static Vector vecDevices=new Vector();
  private static String connectionURL=null;
  public static void main(String[] args) throws IOException
  {
    SampleSPPClient client=new SampleSPPClient();
    //display local device address and name
    LocalDevice localDevice = LocalDevice.getLocalDevice();
    System.out.println("Address: " + localDevice.getBluetoothAddress());
    System.out.println("Name: " + localDevice.getFriendlyName());
    //find devices
    DiscoveryAgent agent = localDevice.getDiscoveryAgent();
    System.out.println("Starting device inquiry...");
    agent.startInquiry(DiscoveryAgent.GIAC, client);

    try
    {
      synchronized(lock)
      {
        lock.wait();
      }
    }
    catch (InterruptedException e)
    {
      e.printStackTrace();
    }

    System.out.println("Device Inquiry Completed. ");
    //print all devices in vecDevices
    int deviceCount=vecDevices.size();

    if(deviceCount <= 0)
    {
      System.out.println("No Devices Found .");
      System.exit(0);
    } else {
      //print bluetooth device addresses and names in the format [ No. address (name) ]
      System.out.println("Bluetooth Devices: ");

      for (int i = 0; i <deviceCount; i++)
      {
        RemoteDevice remoteDevice=(RemoteDevice)vecDevices.elementAt(i);
        System.out.println((i+1) + ". " +
            remoteDevice.getBluetoothAddress() + " (" +
            remoteDevice.getFriendlyName(true) + ")");
      }
    }

    System.out.print("Choose Device index: ");
    BufferedReader bReader =
        new BufferedReader(new InputStreamReader(System.in));
    String chosenIndex = bReader.readLine();
    int index=Integer.parseInt(chosenIndex.trim());
    //check for spp service
    RemoteDevice remoteDevice = (RemoteDevice)vecDevices.elementAt(index-1);
    UUID[] uuidSet = new UUID[1];
    uuidSet[0]=new UUID("1101",false);
    System.out.println("\nSearching for service...");
    agent.searchServices(null,uuidSet,remoteDevice,client);

    try
    {
      synchronized(lock)
      {
        lock.wait();
      }
    }
    catch (InterruptedException e)
    {
      e.printStackTrace();
    }

    if(connectionURL==null)
    {
      System.out.println("Device does not support Simple SPP Service.");
      System.exit(0);
    }

    //connect to the server and send a line of text
    StreamConnection streamConnection =
        (StreamConnection)Connector.open(connectionURL);
    //send string
    OutputStream outStream=streamConnection.openOutputStream();
    PrintWriter pWriter = new PrintWriter(new OutputStreamWriter(outStream));
    pWriter.write("Test String from SPP Client\r\n");
    pWriter.flush();
    //read response
    InputStream inStream=streamConnection.openInputStream();
    BufferedReader bReader2=new BufferedReader(new InputStreamReader(inStream));
    String lineRead=bReader2.readLine();
    System.out.println(lineRead);
  } //main

  //methods of DiscoveryListener
  public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod)
  {
    //add the device to the vector
    if(!vecDevices.contains(btDevice))
    {
      vecDevices.addElement(btDevice);
    }
  }

  //implement this method since services are not being discovered
  public void servicesDiscovered(int transID, ServiceRecord[] servRecord)
  {
    if(servRecord!=null && servRecord.length>0)
    {
      connectionURL=servRecord[0].getConnectionURL(0,false);
    }

    synchronized(lock)
    {
      lock.notify();
    }
  }

  //implement this method since services are not being discovered
  public void serviceSearchCompleted(int transID, int respCode)
  {
    synchronized(lock)
    {
      lock.notify();
    }
  }

  public void inquiryCompleted(int discType)
  {
     synchronized(lock)
     {
       lock.notify();
     }
  }//end method
}
Posted
Updated 25-Feb-10 23:17pm
v3

1 solution

you have to avtivate your SPP : serial port protocol service if you look to the code more carefully you will notice that your UUID :1101 that is a SPP ID , so when you add a new device in your bluetooth shoose from the properites to active SPP service which is FTP file transfet protocol , then you can get a file from the client

you can active more than services the btspp protocol have many services
look at this UUID :

VB
private static final UUID[] searchUuidSet = new UUID[] {
//      new UUID(0x0001),   // SDP
//      new UUID(0x0003),   // RFCOMM
//      new UUID(0x0008),   // OBEX
//      new UUID(0x000C),   // HTTP
        new UUID(0x0100)    // L2CAP
//      new UUID(0x000F),   // BNEP
//      new UUID(0x1101),   // Serial Port ///  ssp   taba3naaa  ..
//      new UUID(0x1000),   // ServiceDiscoveryServerServiceClassID
//      new UUID(0x1001),   // BrowseGroupDescriptorServiceClassID
//      new UUID(0x1002),   // PublicBrowseGroup
//      new UUID(0x1105),   // OBEX Oject Push
//      new UUID(0x1106),   // OBEX File Transfer
//      new UUID(0x1115),   // PAN
//      new UUID(0x1116),   // Network Access Point
//      new UUID(0x1117),   // Group Network



String url = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT,
false);

//Later, after service discovery is complete, I attempt to connect like this:

Connection connection = Connector.open(url);





don't foget to add the url , if you forget it , it will be null and the spp service will not activate
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900