Google

Monday, February 9, 2009

Bluetooth J2SE Server

Use this server with the J2ME Client

/*
* J2SE Server - to start listening from for connections from
* Mobile Phones and receive a string and display it
*/
package j2seserver;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

public class J2SEServer {

public static void main(String[] ags) throws BluetoothStateException, IOException {
new J2SEServer().startServer();
}

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);
}

System.out.println(out.toString());
}
}