JSR-82 Sample : SPP Server and Client
- Posted by Bruse
- 59 Comments »
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 23rd, 2007 at 8:42 pm
Is it a problem to develop the server so it support multi clients?
(to make each connection in different thread)
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.
January 3rd, 2008 at 8:56 pm
I'm not too comfortable with line 133 of the client (condition of the if statement). Because:
1.) servRecord can never be null
2.) if servRecord were ever null, the servRecord.length would cause a NullPointerException
Please fix. Bye.
January 3rd, 2008 at 9:00 pm
Oh, and by the way, your web site help me very much in my project. Thanks
January 8th, 2008 at 7:22 pm
i am trying to create a aplication so that i can send images and text from my pc to cell phones, so i have to use my pc as a client for cell phone services?can i use the client you wrote here in my pc?
February 12th, 2008 at 1:25 pm
anyone can tell me more about this code. it can connection between pc(server) to pc (client).
i want to sent text message from pc to another pc.this code can use for my purpose?
February 21st, 2008 at 9:39 pm
Hello
I want comlete this code for chating to person with each other ..can you complete the code for me if i want to put some method in this code for runing this code ??
thankx
March 6th, 2008 at 10:38 pm
"Just remove/replace those codes that reads the input from the user (PrintWriter/BufferedReader), and the code will work with J2ME"
What do you replace them with? Can you give a bit more detail please? I'm new to Java J2ME
March 10th, 2008 at 7:21 am
Can any one tell me how I can test this example code in WTK 2.5.2? Thanks in advance.
March 17th, 2008 at 11:37 am
BY what kind of methods can we replace PrintWriter/BufferedReader
with J2ME???
April 2nd, 2008 at 3:43 am
hello.. i want to develop mobile learning using bluetooth connection.. mobile phone-clients and laptop-server.. what type interfaces that i must use in client site and server site?? can i know??
April 11th, 2008 at 10:46 am
I'm running the client and server code that you posted but I have this two problems:
1)Neither of the two programms will terminate they keep on running
2)The server prints null as for the friendly device name
-Remote device name: null
I'm using blueSim for both client and server
Also for the client to run I had to change: uuidSet[0]=new UUID("1101",false);
to true otherwise I get:
Searching for service...
Device does not support Simple SPP Service.
Thanks
April 19th, 2008 at 9:39 pm
so how are we supposed to remove the (PrintWriter/BufferedReader) so that the code still works? what do we replace it with?
May 2nd, 2008 at 4:24 pm
I´ve tray it but when I start the client always say that the dispositive does not support SPP I saw that is bcause the string connectionURL is always on NULL could somebody tellme how to fix this ???
July 7th, 2008 at 1:20 pm
does this work?
July 8th, 2008 at 9:42 am
Client works fine, however in order to connect to the Server what will i make the connectionURL?
Because at the moment the Server just waits for an incoming connection.
July 18th, 2008 at 2:10 am
please write about communicating over bluetooth between HP-PC and otherwise. send text,image or sound. i'm waiting your release..
August 1st, 2008 at 8:42 pm
Is it possible get more than one client connected to the server?
August 5th, 2008 at 6:40 pm
Hello..
Excuse me ,How can I add the:
javax.bluetooth.*
package?
Thanks..
August 6th, 2008 at 7:29 pm
Hi,
can someone provide me with help? I'm trying to implement a simple app like in the example, but at the line:
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );
I'm getting an exception:
Exception in thread "main" java.lang.UnsatisfiedLinkError: com.sun.midp.Configuration.getProperty0(Ljava/lang/String;)Ljava/lang/String;
at com.sun.midp.Configuration.getProperty0(Native Method)
at com.sun.midp.Configuration.getProperty(Configuration.java:34)
at com.sun.midp.io.InternalConnector.(InternalConnector.java:91)
at javax.microedition.io.Connector.open(Connector.java:158)
at javax.microedition.io.Connector.open(Connector.java:138)
at javax.microedition.io.Connector.open(Connector.java:120)
at darkblueremoteserver.Server.run(Server.java:27)
at java.lang.Thread.run(Unknown Source)
at darkblueremoteserver.Main.main(Main.java:22)
My environment:
OS: Windows XP SP2
Java: jdk1.6.0_02
IDE: NetBeans 6.0.1
From WTK22 "lib" and "wtklib" folders, the following JARs are added to my project's compile and run time:
cldcapi10.jar
cldcapi11.jar
j2me-ws.jar
jsr082.jar
jsr184.jar
jsr75.jar
midpapi10.jar
midpapi20.jar
mmapi.jar
wma11.jar
wma20.jar
customjmf.jar
gcf-op.jar
kdp.jar
kvem.jar
lime.jar
September 12th, 2008 at 3:39 pm
I am running this program on two laptops. The server on one, and the client on the other. I run the server, and it says waiting for incoming connections. Then, I run the client, it shows the bluetooth devices, and asks me to select an index. I choose the laptop that has the server running, and then it says "Device does not support Simple SPP Service". I don't understand because I didn't change anything in the code, so why is it not working?
November 13th, 2008 at 2:48 pm
I want to create a simple app, All app client and server on same time. (One thread create a server and waiting the client, and another try to find servers). I this case in the emulator work correctly but in two SE v640i no (the inquiry not found the devices etc...). How can I solve this problem?
December 23rd, 2008 at 11:55 pm
Hello mate
I am trying to run your codes on J2SE but i am getting a problem on line 84 of the client code (uuidSet[0]=new UUID("1101",false);) i keep getting the following exception when i select a device index heres the output:
--------------------Configuration: --------------------
avetanaBluetooth version 1.3.18a
Address: 000B0D09F952
Name: NAZLAPTOP
Starting device inquiry...
Device Inquiry Completed.
Bluetooth Devices:
1. 00066E1005E4 (COMPUTER)
2. 0017E871DD39 (saddaf)
3. 001E3A1E9FE3 (Fazza)
4. 0022FCB36728 (Nazruls phone)
Choose Device index: 4
index is = 4
Got to line 84 [Ljavax.bluetooth.UUID;@1ccb029
Exception in thread "main" java.lang.IllegalArgumentException: A 128-bits UUID must be a 32 character long String!!
at javax.bluetooth.UUID.(UUID.java:170)
at SampleSPPClient.main(SampleSPPClient.java:85)
Local Name NAZLAPTOP
Local Address 00:0B:0D:09:F9:52
Local Device class 20104
Valid until 05.01.2009
LicenseID 9694
Possibilities 3f
Process completed.
Can you please help me with this.
Thanks
Naz
March 2nd, 2009 at 7:19 pm
hi all,
i tried similar code.when i run client and server on emulator then it runs fine...
but when i run server on emulator and client on a nokia 7610, it does not work...please help me out...
thanks in advance
March 11th, 2009 at 6:43 pm
Hello, how can I connect multiples client to server?
March 15th, 2009 at 12:11 pm
Hi,
I already edited my localDevice attribute value for 0x0100... as...
record.setAttributeValue(0x0101, new DataElement(DataElement.STRING, attributeValue));
but I cannot retrieve this values from a remotedevice... how can I retrieve it?
thanks.
March 18th, 2009 at 3:02 am
how to run this code?
March 18th, 2009 at 3:50 am
I mean the client code
March 31st, 2009 at 4:05 pm
I think there is a mistake in client code example. Replace "false" with "true" in line 85. Now Client and Server have the same UUID, so they are able to connect.
But thank you a lot for publishing this code. It was the most helpful example I have found.
April 13th, 2009 at 11:23 am
I am also running this program on two laptops as Gage. The server on one, and the client on the other. I run the server, and it says waiting for incoming connections. Then, I run the client, it shows the bluetooth devices, and asks me to select an index. I choose the laptop that has the server running, and then it says "Device does not support Simple SPP Service". I don't understand because I didn't change anything in the code, so why is it not working?
I also want to ask about the required environment for this code to work in such a perfect way!!
April 20th, 2009 at 6:25 pm
Gage: (23rd post):
Yes, I get exactly the same
error.
My suspicion is that the 'localhost:' that is part of the server's URL might be a problem, since that seems to imply that we're only gonna allow connections from
the local-machine.
Not yet sure what the fix for that would be: e.g. just remove that?
Does anyone have it working
between two separate PCs?
April 28th, 2009 at 6:33 am
Same error as 23rd and 32rd post.
@cookdav:'localhost' cannot be the problem because it is needed to identify the service as a host.Without it, it would become a client service.
However, i doubt whether the service is successfully getting registered in the server.The following modification in the client fails to discover the above mentioned service in the server:
line 131:
//implement this method since services are not being discovered
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
if(servRecord!=null && servRecord.length>0){
for(int i=0;i<servRecord.length;i++){
connectionURL=servRecord[i].getConnectionURL(0,true);
System.out.println("+++++++"+connectionURL+"+++++++++++");
}
}
May 6th, 2009 at 1:09 pm
anyone made this multithreaded to connect to multiple mobiles?
June 3rd, 2009 at 7:41 pm
The client code always selects the first service to connect to:
connectionURL=servRecord[0].getConnectionURL(0,false);
However - what should I do if I have two spp services? I'm using Motorola i876 and I have two spp services and I must select one of them.
I thought that the connectionUrl found in the client will be the same as published by the server, but they are completely different. In particular, there is no "Sample SPP Server" name in the connection string.
What should I do?
June 4th, 2009 at 3:57 pm
Im developing a apps for communicate with a Bluetooth Module, i dont know how to get connect with him, because i cant programm the module with Java, the apps is for a cellphone. Any Help???
June 10th, 2009 at 4:18 pm
Hi
Thank u so much for publishing this code, it was very much useful to me.
To this I have implemented Thread to get multiple request. But, for java client it is working fine.
But I am facing problem in Window Mobile. If i increase thread.sleep(5000), it is working fine.
Can anyone please tell, where the issue is.
Thanks
Veena
June 11th, 2009 at 3:56 am
hi all
Is there is any need to make thread.sleep(4000) after sending response to client or flushing the stream.
For Windows client if i implement the thread.sleep(4000) after sending response, application is working but not working for Java Client.
If i remove thread.sleep, application running fine in java client.
Please help me
Regards
Sidha
....
System.out.println("After send to Client -->" + slimResponse.trim());
Thread.sleep(4000);
out.close();
out.flush();
.............
}
June 18th, 2009 at 6:58 pm
line 85 uuidSet[0]=new UUID("1101",false);
try:
uuidSet[0]=new UUID(0x1101);
June 29th, 2009 at 9:07 am
hi all,
im trying to run the code ..but as i found that it does not work in j2me.. how to make it work?
can anyone help me? what to replace . I was trying to trace the reply for this but no one had replied to...
plss...
Re:
"Just remove/replace those codes that reads the input from the user (PrintWriter/BufferedReader), and the code will work with J2ME"
July 3rd, 2009 at 11:41 am
Hello! Can you help me with making connection between a PC (with J2SE) and a mobile phone (with J2ME)?
I can't understand how the method getLocalDevice works (it always causes an exception on PC). Would be great if you explained me how to work with PC's bluetooth adapter, because it's turned on, but getLocalDevice still do not work
July 10th, 2009 at 1:58 pm
For those whoc cannot run correctly the client ( Device doesn't support Simple SPP Service), change uudiSet[0] to uuidSet[0]= new UUID("1101",true) (mistake if not) and if it still doesn't work, add this line:
int[] attrSet={0x1101};
and when call for agent.searchServices, replace the first arg "null" to attrSet mentioned above.
July 10th, 2009 at 11:57 pm
Hye I am working on a project which requires me reading a sensor data from a bluetooth chip embedded with it. So should I use Serial Port profile and how do I find out UUID of the connection. Please help urgently required! Is it necessary to use a client server configuration?
July 28th, 2009 at 5:15 am
ahmm i just want to ask if any one here know how to connect bluetooth server to My document..plz pm me..
July 31st, 2009 at 11:51 am
plz help me
my code is given below. and i am stuck at that point to search the services of a bluetooth device.
i dont know y it is going fail to search the services.
here is my code and after this u can see the console output
try {
System.out.println(attributes);
System.out.println(uuids);
System.out.println(device);
agent.searchServices(attributes,uuids,device,this);
} catch (BluetoothStateException e) {}
Console out put
[I@1cb37664
[Ljavax.bluetooth.UUID;@f828ed68
RemoteDevice[address=0000000DECAF, name=null, encrypted=false, authenticated=false]
java.lang.NullPointerException
at com.sun.kvem.jsr082.bluetooth.DataL2CAPReaderWriter.(+41)
at com.sun.kvem.jsr082.bluetooth.SDPClient$SDPTransport.start(+100)
at com.sun.kvem.jsr082.bluetooth.SDPClient.openTransport(+94)
at com.sun.kvem.jsr082.bluetooth.SDPClient.open(+41)
at com.sun.kvem.jsr082.bluetooth.SDPClient.(+9)
at com.sun.kvem.jsr082.bluetooth.ServiceSearcher.start(+110)
at com.sun.kvem.jsr082.bluetooth.DiscoveryAgentImpl.searchServices(+19)
at javax.bluetooth.DiscoveryAgent.searchServices(+12)
at YourMIDlet.doServiceSearch(+72)
at YourMIDlet.deviceDiscovered(+61)
at com.sun.kvem.jsr082.impl.bluetooth.BTDeviceDiscoverer.run(+268)
Inquiry Completed
August 17th, 2009 at 4:18 pm
Pls if I want to send multiple messages between the server and Client, how do I do that.
Thanks
September 11th, 2009 at 5:43 pm
I modify this code so i can chat between client and server , but they can exchange messages for one time only i don't know why ?? any one can help please
September 14th, 2009 at 2:28 pm
Pls if I want to send multiple messages between the server and Client, how do I do that.
(now just i can send a single message between client and server)
October 27th, 2009 at 12:09 pm
when i run this code i got error in PrintWriter and BufferedWriter it shows-it can not be resolved to a type.
Now what can ido to remove this error??java.io.PrintWriter and java.io.BufferedReader are not present in java.io.Plz solve my problem as it is my project.
Thanking you.
November 12th, 2009 at 5:12 am
i tried this code in j2me but get errors: bufferedreader and printwriter can not be resolved to a type. how can i solve this problem?plz help me .
thanks.
November 16th, 2009 at 1:09 pm
plz tell me how to send image from server to client??through bluetooth??
December 26th, 2009 at 5:50 pm
hi I want to create app that it will use Mylaptop bluetooh and it will search the others like pohnes and other laptops bluetooth mac addresses.is this project works only on J2ME ? cant i run it on my computer as a API?
January 11th, 2010 at 2:05 am
@Siddiqi
I have been sat at my desk for almost 4 hours trying to solve the NullPointerException problem when searching for services. I was *just* about to give up when I tried changing the platform (emulator) that was executing my code. I am using NetBeans 6.7.1 and was originally using the "Default colour phone" platform. I switched to the "Qwerty device" platform and the issue was instantly resolved. I know the posts on here are somewhat old but there's such a lack of information regarding JSR-82 on the net I thought I'd do my part.
Happy coding everyone
January 22nd, 2010 at 3:11 pm
hi to all, how can I set a path for ElectricBlue?
my project give me this error:
Include ElectricBlue library in the path at com.jsrsoft.eb.nw.NW.
February 6th, 2010 at 9:49 pm
Hi,
I have a problem that after sending the text from the client to an other device (line 111 in the client code) the program crashed with the error:
Invalid memory access of location 0x5fbfd41c rip=0x11454803a
Java Result: 139
The text has been transmitted correctly to the other device.
OS: Mac OSX 10.6.2
Java: 1.6.0_17
IDE: Netbeans 6.8
Has anybody else seen this issue or know of a workaround?
Thanks,
wipo
February 23rd, 2010 at 6:39 am
Hii,
is his possible to to make a pair of two client???
one client is pc(J2SE) and another Client is mobile(J2ME)....
Both will Connect with Each Other...
Is this Possible????
Thanks,
Rajesh Parmar
February 26th, 2010 at 5:36 am
hi.. i tried this code server client where not connect? i'm using bluetooth dongle for connection? client could not detect server? please help me?
March 2nd, 2010 at 12:18 am
I ve just changed UUID("1101",false)to UUID("1101",true) and then it works for me very well