Google

Monday, February 9, 2009

Bluetooth J2ME Server

Use this Server with the J2ME Client

/*
* J2ME Server Midlet to accept incoming connection and a string
* from the J2ME Client counterpart
*/

package j2meserver;

import java.io.*;
import javax.bluetooth.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class J2MEServerMidlet extends MIDlet implements CommandListener,Runnable{
Form f;
Command cmExit,cmListen;
Thread t;
Display d;
public J2MEServerMidlet(){
f=new Form("J2ME Server");
cmExit=new Command("Exit",Command.EXIT,1);
cmListen=new Command("Listen",Command.SCREEN,2);
f.addCommand(cmExit);
f.addCommand(cmListen);
f.setCommandListener(this);
}
public void startApp() {
if (d == null) {
d = Display.getDisplay(this);
d.setCurrent(f);
t = new Thread(this);
}
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void commandAction(Command c, Displayable d) {
if(c==cmExit){
destroyApp(false);
notifyDestroyed();
}
if(c==cmListen){
t.start();
}
}

public void run() {
try {
startServer();
} catch (BluetoothStateException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}

private void startServer() throws BluetoothStateException, IOException {
LocalDevice local = LocalDevice.getLocalDevice();
if (!local.setDiscoverable(DiscoveryAgent.GIAC)) {
System.out.println("Failed to change to the " + "discoverable mode");
}

// Create a server connection object to accept
// a connection from a client
StreamConnectionNotifier notifier =
(StreamConnectionNotifier) Connector.open("btspp://localhost:" +
"86b4d249fb8844d6a756ec265dd1f6a3");

// Accept a connection from the client
StreamConnection conn = notifier.acceptAndOpen();

// Open the input to read data from
InputStream in = conn.openInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();

// Read the data sent from the client until
// the end of stream
int data;
while ((data = in.read()) != -1) {
out.write(data);
}
f.append("Received: ");
f.append(out.toString());
}
}