JSR-82 Sample : SPP Server and Client
- Posted by Bruse
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.
-
//Create a UUID for SPP
-
UUID uuid = new UUID("1101", true);
-
//Create the servicve url
- Registering service and Waiting for Client connection.
-
//open server url
-
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );
-
//Wait for client connection
-
StreamConnection connection=streamConnNotifier.acceptAndOpen ();
- Communicate with the client
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
The next step is to register for the service and to wait for client connection. This step is achieved by the following codes
The acceptAndOpen method waits until a client is connected.
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.
- Connect to server
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
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
-
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.*;
-
-
/**
-
* Class that implements an SPP Server which accepts single line of
-
* message from an SPP client and sends a single line of response to the client.
-
*/
-
public class SampleSPPServer {
-
-
//start server
-
-
//Create a UUID for SPP
-
UUID uuid = new UUID("1101", true);
-
//Create the servicve url
-
-
//open server url
-
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );
-
-
//Wait for client connection
-
StreamConnection connection=streamConnNotifier.acceptAndOpen();
-
-
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
-
-
//read string from spp client
-
-
//send response to spp client
-
pWriter.write("Response String from SPP Server\r\n");
-
pWriter.flush();
-
-
pWriter.close();
-
streamConnNotifier.close();
-
-
}
-
-
-
-
//display local device address and name
-
LocalDevice localDevice = LocalDevice.getLocalDevice();
-
-
SampleSPPServer sampleSPPServer=new SampleSPPServer();
-
sampleSPPServer.startServer();
-
-
}
-
}
SPP Client Source Code
-
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;
-
-
/**
-
* A simple SPP client that connects with an SPP server
-
*/
-
public class SampleSPPClient implements DiscoveryListener{
-
-
//object used for waiting
-
-
//vector containing the devices discovered
-
-
-
-
SampleSPPClient client=new SampleSPPClient();
-
-
//display local device address and name
-
LocalDevice localDevice = LocalDevice.getLocalDevice();
-
-
//find devices
-
DiscoveryAgent agent = localDevice.getDiscoveryAgent();
-
-
agent.startInquiry(DiscoveryAgent.GIAC, client);
-
-
try {
-
synchronized(lock){
-
lock.wait();
-
}
-
}
-
e.printStackTrace();
-
}
-
-
-
-
//print all devices in vecDevices
-
int deviceCount=vecDevices.size();
-
-
if(deviceCount <= 0){
-
}
-
else{
-
//print bluetooth device addresses and names in the format [ No. address (name) ]
-
for (int i = 0; i <deviceCount; i++) {
-
RemoteDevice remoteDevice=(RemoteDevice)vecDevices.elementAt(i);
-
System.out.println((i+1)+". "+remoteDevice.getBluetoothAddress()+" ("+remoteDevice.getFriendlyName(true)+")");
-
}
-
}
-
-
-
-
//check for spp service
-
RemoteDevice remoteDevice=(RemoteDevice)vecDevices.elementAt(index-1);
-
UUID[] uuidSet = new UUID[1];
-
uuidSet[0]=new UUID("1101",false);
-
-
agent.searchServices(null,uuidSet,remoteDevice,client);
-
-
try {
-
synchronized(lock){
-
lock.wait();
-
}
-
}
-
e.printStackTrace();
-
}
-
-
if(connectionURL==null){
-
}
-
-
//connect to the server and send a line of text
-
StreamConnection streamConnection=(StreamConnection)Connector.open(connectionURL);
-
-
//send string
-
pWriter.write("Test String from SPP Client\r\n");
-
pWriter.flush();
-
-
-
//read response
-
-
-
}//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
-
-
-
-
}

November 27th, 2007 at 12:01 am
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
December 18th, 2007 at 3:48 pm
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
December 30th, 2007 at 7:44 pm
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.