chat using bluetooth

hi all,

I'm doing my final year exam

about chat between client n server

but the message was sent by another bluetooth device

client used that bluetooth device to find server n send the message

while server used it to send message only

the problem, my application couldn't send twice or more

could anyone help me?

here is the source code: (you can change the code or anything)

[433 byte] By [skylancera] at [2007-11-27 5:19:43]
# 1

import java.io.ByteArrayOutputStream;

import java.io.InputStream;

import java.io.IOException;

import java.io.OutputStream;

import javax.bluetooth.BluetoothStateException;

import javax.bluetooth.DiscoveryAgent;

import javax.bluetooth.LocalDevice;

import javax.bluetooth.L2CAPConnection;

import javax.bluetooth.L2CAPConnectionNotifier;

import javax.bluetooth.RemoteDevice;

import javax.bluetooth.ServiceRecord;

import javax.bluetooth.UUID;

import javax.microedition.io.Connector;

import javax.microedition.io.StreamConnection;

import javax.microedition.lcdui.Alert;

import javax.microedition.lcdui.Choice;

import javax.microedition.lcdui.ChoiceGroup;

import javax.microedition.lcdui.Command;

import javax.microedition.lcdui.CommandListener;

import javax.microedition.lcdui.Display;

import javax.microedition.lcdui.Displayable;

import javax.microedition.lcdui.Form;

import javax.microedition.lcdui.List;

import javax.microedition.lcdui.StringItem;

import javax.microedition.lcdui.TextField;

import javax.microedition.midlet.MIDlet;

public class BlueReplicationMIDlet extends MIDlet implements CommandListener

{

public static final String UUID_STRING = "11112233445566778899AABBCCDDEEFF";

private static final String[] FIRSTMENU = {"Chat", "Chat with Repeater"};

private static final String[] SECONDMENU = {"Server", "Connect"};

private static final String[] THIRDMENU = {"Server", "Connect", "Repeater"};

private LocalDevice localDevice = null;

private DiscoveryAgent discoveryAgent = null;

private L2CAPConnection conn = null;

private RemoteDevice[] remoteDevices = null;

private StringItem status = new StringItem("status:", null);

private final Form chatUI = new Form("Chat");

private final List welcomeList = new List("Bluetooth Repeater Application", List.IMPLICIT, FIRSTMENU, null);

private final List roleListWithRepeater = new List("Chat with Repeater", List.IMPLICIT, THIRDMENU, null);

private final ChoiceGroup devices = new ChoiceGroup(null, Choice.EXCLUSIVE);

private final Command backCommand = new Command("Back", Command.BACK, 1);

private final Command exitCommand = new Command("Exit", Command.EXIT, 1);

private final Command startCommand = new Command("Start Server", Command.SCREEN, 1);

private final Command connectCommand = new Command("Connect to server", Command.SCREEN, 1);

private final Command selectCommand = new Command("Select", Command.SCREEN, 1);

private final Command sendCommand = new Command("Send", Command.SCREEN, 1);

private final TextField incoming = new TextField("Incoming", "", 256, TextField.UNEDITABLE);

private final TextField outgoing = new TextField("Outgoing", "", 256, TextField.ANY);

private boolean running = false;

public BlueReplicationMIDlet()

{

welcomeList.addCommand(exitCommand);

welcomeList.setCommandListener(this);

}

public void startApp()

{

getDisplayUI().setCurrent(welcomeList);

}

public void pauseApp()

{}

public void destroyApp(boolean unconditional)

{}

public void commandAction(Command c, Displayable d)

{

if (c == exitCommand)

{

running = false;

exit();

return;

}

else if (d == welcomeList)

{

if (c == List.SELECT_COMMAND)

{

try

{

localDevice = LocalDevice.getLocalDevice();

discoveryAgent = localDevice.getDiscoveryAgent();

}

catch (BluetoothStateException bse)

{

doAlert("Bluetooth Exception : " + "Unable to start", errorTime());

notifyDestroyed();

}

int index = welcomeList.getSelectedIndex();

switch (index)

{

case 0:

running = true;

chatUI.append(status);

chatUI.addCommand(startCommand);

chatUI.addCommand(connectCommand);

chatUI.setCommandListener(this);

chatUI.addCommand(backCommand);

getDisplayUI().setCurrent(chatUI);

break;

case 1:

roleListWithRepeater.addCommand(backCommand);

roleListWithRepeater.setCommandListener(this);

getDisplayUI().setCurrent(roleListWithRepeater);

break;

}

}

}

else if (d == chatUI)

{

if (c == startCommand)

{

new Thread()

{

public void run()

{

startServer();

}

}.start();

}

else if (c == connectCommand)

{

status.setText("Searching for devices...");

chatUI.removeCommand(connectCommand);

chatUI.removeCommand(startCommand);

chatUI.append(devices);

DeviceDiscoverer discoverer = new DeviceDiscoverer(BlueReplicationMIDlet.this);

try

{

//non-blocking

discoveryAgent.startInquiry(DiscoveryAgent.GIAC, discoverer);

}

catch (BluetoothStateException bse)

{

status.setText("BSException : " + bse.toString());

}

}

else if (c == selectCommand)

{

status.setText("Searching device for service");

int index = devices.getSelectedIndex();

chatUI.delete(chatUI.size()-1);//delete choice group

chatUI.removeCommand(selectCommand);

ServiceDiscoverer serviceDiscoverer = new ServiceDiscoverer(BlueReplicationMIDlet.this);

int[] attrSet = {0x100};//return service name attribute

UUID[] uuidSet = new UUID[1];

uuidSet[0] = new UUID(UUID_STRING, false);

try

{

//non-blocking

discoveryAgent.searchServices(attrSet, uuidSet, remoteDevices[index], serviceDiscoverer);

}

catch (BluetoothStateException bse)

{

status.setText("Bluetooth Exception : "+bse.toString());

}

}

else if (c == sendCommand)

{

new Thread()

{

public void run()

{

sendMessage();

}

}.start();

}

else if (c == backCommand)

{

getDisplayUI().setCurrent(welcomeList);

}

}

else if (d == roleListWithRepeater)

{

if (c == List.SELECT_COMMAND)

{

int index = roleListWithRepeater.getSelectedIndex();

switch (index)

{

case 0:

//System.out.println("Server");

Server server = new Server(this);

break;

case 1:

//System.out.println("Connect");

Client client = new Client(this);

break;

case 2:

//System.out.println("Repeater");

Repeater repeater = new Repeater(this);

break;

}

}

else if (c == backCommand)

{

getDisplayUI().setCurrent(welcomeList);

}

}

}

public void exit()

{

getDisplayUI().setCurrent(null);

destroyApp(true);

notifyDestroyed();

}

public Display getDisplayUI()

{

return Display.getDisplay(this);

}

public int errorTime()

{

return 8000;

}

public void releaseResources()

{

try

{

if (conn != null)

conn.close();

}

catch(IOException ioe)

{

doAlert("IOException : " + ioe.toString(), errorTime());

}

}

public String getCode(String code)

{

int i = code.indexOf('-', 0);

return (code.substring(0, i - 1));

}

public String getBluetoothReceiver(String bluetoothReceiver)

{

int i = bluetoothReceiver.indexOf('-', 0);

int j = bluetoothReceiver.indexOf('=', 0);

return (bluetoothReceiver.substring(i + 2, j - 1));

}

public String getMessage(String text)

{

int i = text.indexOf('=', 0);

return (text.substring(i + 2, text.length()));

}

public RemoteDevice makeRemoteDevice(String bluetoothReceiver)

{

BluetoothRemoteDevice bluetoothRemoteDevice = new BluetoothRemoteDevice(bluetoothReceiver);

return bluetoothRemoteDevice;

}

public String readMessage(StreamConnection conn)

{

try

{

int data;

InputStream in = conn.openInputStream();

ByteArrayOutputStream out = new ByteArrayOutputStream();

while ((data = in.read()) != -1)

{

out.write(data);

}

return out.toString();

}

catch (Exception ex)

{

doAlert("Exception : "+ex.toString(), errorTime());

return null;

}

}

public void sendMessage(String message, String serviceURL)

{

try

{

boolean timeOut = true;

StreamConnection conn = (StreamConnection)Connector.open(serviceURL, Connector.READ_WRITE, timeOut);

OutputStream out = conn.openOutputStream();

out.write(message.getBytes());

out.close();

conn.close();

}

catch (Exception ex)

{

doAlert("Exception : "+ex.toString(), errorTime());

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

}

}

public void doAlert(String msg, int timeOut)

{

if (getDisplayUI().getCurrent() instanceof Alert)

{

((Alert) getDisplayUI().getCurrent()).setString(msg);

((Alert) getDisplayUI().getCurrent()).setTimeout(timeOut);

}

else

{

Alert alert = new Alert("Bluetooth");

alert.setString(msg);

alert.setTimeout(timeOut);

getDisplayUI().setCurrent(alert);

}

}

public void startServer()

{

status.setText("Server starting...");

chatUI.removeCommand(connectCommand);

chatUI.removeCommand(startCommand);

try

{

localDevice.setDiscoverable(DiscoveryAgent.GIAC);

L2CAPConnectionNotifier notifier = (L2CAPConnectionNotifier)Connector.open("btl2cap://localhost:" + UUID_STRING + ";name=L2CAPchat");

ServiceRecord record = localDevice.getRecord(notifier);

String connURL = record.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);

status.setText("Server running");

conn = notifier.acceptAndOpen();//record is saved to the SDDB on this call

new Thread()

{

public void run()

{

startReceiver();

}

}.start();

}

catch (IOException ioe)

{

status.setText("IOException: " + ioe.toString());

}

}

public void startReceiver()

{

chatUI.addCommand(sendCommand);

chatUI.append(incoming);

chatUI.append(outgoing);

while (running)

{

try

{

if (conn.ready())

{

int receiveMTU = conn.getReceiveMTU();

byte[] data = new byte[receiveMTU];

int length = conn.receive(data);

String message = new String(data, 0, length);

incoming.setString(message);

}

}

catch (IOException ioe)

{

doAlert("IOException : " + ioe.toString(), errorTime());

}

}

}

public void sendMessage()

{

try

{

String message = outgoing.getString();

byte[] data = message.getBytes();

int transmitMTU = conn.getTransmitMTU();

if (data.length <= transmitMTU)

{

conn.send(data);

}

else

{

status.setText("Message too long!");

}

}

catch (IOException ioe)

{

status.setText("IOException : " + ioe.toString());

}

}

public void deviceInquiryFinished(RemoteDevice[] remoteDevices, String message)

{

this.remoteDevices = remoteDevices;

String[] names = new String[remoteDevices.length];

for(int i = 0; i < remoteDevices.length; i++)

{

try

{

String name = remoteDevices[i].getFriendlyName(false);

names[i] = name;

}

catch (IOException ioe)

{

status.setText("IOException: " + ioe.toString());

}

}

for (int i = 0; i < names.length; i++)

{

devices.append(names[i], null);

}

chatUI.addCommand(selectCommand);

status.setText(message);

}

public void serviceSearchFinished(ServiceRecord serviceRecord, String message)

{

//this.serviceRecord = servRecord;//cache the service record for future use

status.setText(message);

String url = serviceRecord.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);

try

{

conn = (L2CAPConnection)Connector.open(url);

status.setText("connected");

new Thread()

{

public void run()

{

startReceiver();

}

}.start();

}

catch (IOException ioe)

{

status.setText("IOException : " + ioe.toString());

}

}

}

class BluetoothRemoteDevice extends RemoteDevice

{

public BluetoothRemoteDevice(String address)

{

super(address);

}

}

Message was edited by:

skylancer

skylancera at 2007-7-12 10:43:11 > top of Java-index,Java Essentials,Java Programming...
# 2

import java.util.Vector;

import javax.bluetooth.BluetoothStateException;

import javax.bluetooth.DiscoveryAgent;

import javax.bluetooth.LocalDevice;

import javax.bluetooth.RemoteDevice;

import javax.bluetooth.UUID;

import javax.microedition.io.Connector;

import javax.microedition.io.StreamConnection;

import javax.microedition.io.StreamConnectionNotifier;

import javax.microedition.lcdui.Choice;

import javax.microedition.lcdui.ChoiceGroup;

import javax.microedition.lcdui.Command;

import javax.microedition.lcdui.CommandListener;

import javax.microedition.lcdui.Displayable;

import javax.microedition.lcdui.Form;

import javax.microedition.lcdui.TextField;

class Client implements CommandListener

{

public static final String UUID_STRING = "F0E0D0C0B0A000908070605040302010";

private String info = "Use Longest Inquiry\nto detect bluetooth devices\nthat out of your range\n"+

"using one of bluetooth devices\nthat you selected";

private String bluetoothDevices = ""; //stored bluetooth addresses from longest inquiry

private String bluetoothReceiver = ""; //stored bluetooth address that will be sent message

private BlueReplicationMIDlet midlet = null;

private DeviceDiscoverer deviceDiscoverer = null;

private Vector deviceVector;

private LocalDevice localDevice = null;

private DiscoveryAgent discoveryAgent = null;

private RemoteDevice remoteDeviceSelected = null;

private RemoteDevice[] remoteDevice = null;

private UUID[] uuidSet = null;

private StreamConnection conn = null;

private ChoiceGroup devices = new ChoiceGroup(null, Choice.EXCLUSIVE);

private ChoiceGroup devicesLongestInquiry = new ChoiceGroup(null, Choice.EXCLUSIVE);

private Command exitCommand = new Command("Exit", Command.EXIT, 1);

private Command inquiryCommand = new Command("More Detection", Command.SCREEN, 1);

private Command backCommand = new Command("Back", Command.BACK, 1);

private Command nextCommand = new Command("Next", Command.SCREEN, 1);

private Command infoCommand = new Command("Information", Command.SCREEN, 1);

private Command longestInquiryCommand = new Command("Longest Inquiry", Command.SCREEN, 1);

private Command selectCommand = new Command("Select", Command.SCREEN, 1);

private Command sendCommand = new Command("Send", Command.SCREEN, 1);

private Form clientUI = new Form("Client UI");

private Form detectionUI = new Form("Client UI - Detection");

private Form devicesUI = new Form("Client UI - Detection - Devices");

private Form infoUI= new Form("Information UI");

private Form longestInquiryUI = new Form("Longest Inquiry UI");

private TextField incoming = new TextField("Incoming", "", 256, TextField.UNEDITABLE);

private TextField outgoing = new TextField("Outgoing", "", 256, TextField.ANY);

public Client(BlueReplicationMIDlet midlet)

{

this.midlet = midlet;

midlet.getDisplayUI().setCurrent(clientUI);

clientUI.addCommand(exitCommand);

clientUI.setCommandListener(this);

detectionUI.setCommandListener(this);

devicesUI.setCommandListener(this);

infoUI.setCommandListener(this);

longestInquiryUI.setCommandListener(this);

uuidSet = new UUID[1];

try

{

localDevice = LocalDevice.getLocalDevice();

discoveryAgent = localDevice.getDiscoveryAgent();

}

catch (BluetoothStateException bse)

{

midlet.doAlert("BluetoothStateException : "+bse.toString(), midlet.errorTime());

midlet.exit();

}

doInquiry(clientUI);

}

public void commandAction(Command c, Displayable d)

{

if (c == exitCommand)

{

midlet.exit();

}

else if (d == clientUI)

{

if (c == inquiryCommand)

{

clientUI.removeCommand(inquiryCommand);

doInquiry(clientUI);

}

}

else if (d == detectionUI)

{

if (c == backCommand)

{

discoveryAgent.cancelInquiry(deviceDiscoverer);

clientUI.deleteAll();

detectionUI.deleteAll();

clientUI.addCommand(inquiryCommand);

detectionUI.removeCommand(nextCommand);

midlet.getDisplayUI().setCurrent(clientUI);

}

else if (c == inquiryCommand)

{

detectionUI.deleteAll();

detectionUI.removeCommand(inquiryCommand);

doInquiry(detectionUI);

}

else if (c == nextCommand)

{

devicesUI.append("My name : "+localDevice.getBluetoothAddress());

devicesUI.append(devices);

for (int i=0; i<remoteDevice.length; i++)

{

devices.append(remoteDevice[i].getBluetoothAddress(), null);

}

devicesUI.addCommand(backCommand);

devicesUI.addCommand(longestInquiryCommand);

devicesUI.addCommand(infoCommand);

midlet.getDisplayUI().setCurrent(devicesUI);

}

}

else if (d == devicesUI)

{

if (c == backCommand)

{

midlet.getDisplayUI().setCurrent(detectionUI);

}

else if (c == infoCommand)

{

infoUI.append(info);

infoUI.addCommand(backCommand);

midlet.getDisplayUI().setCurrent(infoUI);

}

else if (c == longestInquiryCommand)

{

for (int i=0; i><remoteDevice.length; i++)

{

if (devices.getString(devices.getSelectedIndex()) == remoteDevice[i].getBluetoothAddress())

{

remoteDeviceSelected = remoteDevice[i];

break;

}

}

uuidSet[0] = new UUID(Repeater.UUID_STRING, false);

ServiceDiscoverer serviceDiscoverer = new ServiceDiscoverer(this, null, null, null);

try

{

discoveryAgent.searchServices(null, uuidSet, remoteDeviceSelected, serviceDiscoverer);

new Thread()

{

public void run()

{

try

{

StreamConnectionNotifier notifier = (StreamConnectionNotifier)Connector.open("btspp://localhost:"+UUID_STRING+";name=Client");

conn = notifier.acceptAndOpen();

midlet.getDisplayUI().setCurrent(longestInquiryUI);

longestInquiryUI.append(devicesLongestInquiry);

longestInquiryUI.addCommand(selectCommand);

bluetoothDevices = midlet.readMessage(conn);

String[] tempBluetoothDevice = new String[7];

int index, counter = 0, i = 0;

while (counter >< bluetoothDevices.length())

{

index = bluetoothDevices.indexOf(" ", counter);

tempBluetoothDevice[i] = bluetoothDevices.substring(counter, index);

counter = index + 1;

i++;

}

for (int j=0; j<i; j++)

{

devicesLongestInquiry.append(tempBluetoothDevice[j], null);

}

}

catch (Exception ex)

{

midlet.doAlert("Exception : "+ex.toString(), midlet.errorTime());

}

}

}.start();

}

catch (Exception ex)

{

midlet.doAlert("Exception : "+ex.toString(), midlet.errorTime());

}

}

}

else if (d == infoUI)

{

if (c == backCommand)

{

infoUI.deleteAll();

infoUI.removeCommand(backCommand);

midlet.getDisplayUI().setCurrent(devicesUI);

}

}

else if (d == longestInquiryUI)

{

if (c == selectCommand)

{

longestInquiryUI.deleteAll();

longestInquiryUI.removeCommand(selectCommand);

longestInquiryUI.append(incoming);

longestInquiryUI.append(outgoing);

longestInquiryUI.addCommand(exitCommand);

longestInquiryUI.addCommand(sendCommand);

bluetoothReceiver = devicesLongestInquiry.getString(devicesLongestInquiry.getSelectedIndex());

longestInquiryUI.append("My name : "+localDevice.getBluetoothAddress());

}

else if (c == sendCommand)

{

final ServiceDiscoverer serviceDiscoverer = new ServiceDiscoverer(this, null, null, null);

new Thread()

{

public void run()

{

uuidSet[0] = new UUID(RepeaterToSendMessage.UUID_STRING, false);

try

{

discoveryAgent.searchServices(null, uuidSet, RemoteDevice.getRemoteDevice(conn), serviceDiscoverer);

StreamConnectionNotifier notifier = (StreamConnectionNotifier)Connector.open("btspp://localhost:"+UUID_STRING+";name=Client");

conn = notifier.acceptAndOpen();

outgoing.setString(midlet.readMessage(conn));

}

catch (Exception ex)

{

midlet.doAlert("Exception : "+ex.toString(), midlet.errorTime());

}

}

}.start();

}

}

}

public void doInquiry(Form frm)

{

try

{

deviceDiscoverer = new DeviceDiscoverer(this, null);

frm.append("Searching for device...");

discoveryAgent.startInquiry(DiscoveryAgent.GIAC, deviceDiscoverer);

}

catch (Exception ex)

{

midlet.doAlert("Exception : "+ex.toString(), midlet.errorTime());

}

}

public void deviceInquiryFinished(Vector deviceVector, String message)

{

remoteDevice = new RemoteDevice[deviceVector.size()];

detectionUI.deleteAll();

detectionUI.addCommand(backCommand);

midlet.getDisplayUI().setCurrent(detectionUI);

if (deviceVector.size() == 0)

{

message = "No Device Detected";

detectionUI.addCommand(inquiryCommand);

}

else

{

for (int i=0; i><deviceVector.size(); i++)

{

remoteDevice[i] = (RemoteDevice)deviceVector.elementAt(i);

}

message = remoteDevice.length+" devices have been discovered\nClick next to go to the next screen";

detectionUI.addCommand(nextCommand);

}

detectionUI.append(message);

}

public void serviceSearchFinished(String message, String serviceURL)

{

midlet.sendMessage("2 - "+bluetoothReceiver+" = "+outgoing.getString(), serviceURL);

}

}

Message was edited by:

skylancer">

skylancera at 2007-7-12 10:43:11 > top of Java-index,Java Essentials,Java Programming...
# 3

import java.util.Vector;

import javax.bluetooth.DeviceClass;

import javax.bluetooth.DiscoveryListener;

import javax.bluetooth.RemoteDevice;

import javax.bluetooth.ServiceRecord;

class DeviceDiscoverer implements DiscoveryListener

{

private Vector deviceVector = null;

private BlueReplicationMIDlet midlet = null;

private Client client = null;

private Repeater repeater = null;

public DeviceDiscoverer(BlueReplicationMIDlet midlet)

{

if (midlet != null)

this.midlet = midlet;

deviceVector = new Vector();

}

public DeviceDiscoverer(Client client, Repeater repeater)

{

if (client != null)

this.client = client;

else if (repeater != null)

this.repeater = repeater;

deviceVector = new Vector();

}

public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass deviceClass)

{

deviceVector.addElement(remoteDevice);

}

public void inquiryCompleted(int discType)

{

String message = null;

if (discType == INQUIRY_COMPLETED)

message = "INQUIRY COMPLETED";

else if (discType == INQUIRY_TERMINATED)

message = "INQUIRY TERMINATED";

else if (discType == INQUIRY_ERROR)

message = "INQUIRY ERROR";

if (midlet != null)

{

RemoteDevice[] devices = new RemoteDevice[deviceVector.size()];

for(int i = 0; i < deviceVector.size(); i++)

{

devices = (RemoteDevice)deviceVector.elementAt(i);

}

midlet.deviceInquiryFinished(devices, message);

deviceVector = null;

midlet = null;

}

else if (client != null)

{

client.deviceInquiryFinished(deviceVector, message);

client = null;

}

else if (repeater != null)

{

repeater.deviceInquiryFinished(deviceVector, message);

repeater = null;

}

deviceVector = null;

}

public void servicesDiscovered(int transID, ServiceRecord[] serviceRecord)

{}

public void serviceSearchCompleted(int transID, int respCode)

{}

}

skylancera at 2007-7-12 10:43:11 > top of Java-index,Java Essentials,Java Programming...
# 4

import java.util.Vector;

import javax.bluetooth.BluetoothStateException;

import javax.bluetooth.DiscoveryAgent;

import javax.bluetooth.LocalDevice;

import javax.bluetooth.RemoteDevice;

import javax.bluetooth.UUID;

import javax.microedition.io.Connector;

import javax.microedition.io.StreamConnection;

import javax.microedition.io.StreamConnectionNotifier;

import javax.microedition.lcdui.Command;

import javax.microedition.lcdui.CommandListener;

import javax.microedition.lcdui.Displayable;

import javax.microedition.lcdui.Form;

class Repeater implements CommandListener

{

public static final String UUID_STRING = "A1A2A3A4A5A6A7A8A9A0B1B2B3B4B5B6";

private String senderName = "";

private String bluetoothDevices = "";

private BlueReplicationMIDlet midlet = null;

private LocalDevice localDevice = null;

private DiscoveryAgent discoveryAgent = null;

private RemoteDevice[] remoteDevice = null;

private UUID[] uuidSet = null;

private StreamConnection conn = null;

private Command exitCommand = new Command("Exit", Command.EXIT, 1);

private Form repeaterUI = new Form("Repeater UI");

public Repeater(BlueReplicationMIDlet midlet)

{

this.midlet = midlet;

midlet.getDisplayUI().setCurrent(repeaterUI);

repeaterUI.addCommand(exitCommand);

repeaterUI.setCommandListener(this);

try

{

localDevice = LocalDevice.getLocalDevice();

discoveryAgent = localDevice.getDiscoveryAgent();

}

catch (BluetoothStateException bse)

{

midlet.doAlert("BluetoothStateException : "+bse.toString(), midlet.errorTime());

midlet.exit();

}

//kode ini nanti dihapus

repeaterUI.append("My Name : "+localDevice.getBluetoothAddress());

//

new Thread()

{

public void run()

{

startRepeater();

}

}.start();

}

public void commandAction(Command c, Displayable d)

{

if (c == exitCommand)

{

midlet.exit();

}

}

public void startRepeater()

{

try

{

localDevice.setDiscoverable(DiscoveryAgent.GIAC);

StreamConnectionNotifier notifier = (StreamConnectionNotifier)Connector.open("btspp://localhost:"+UUID_STRING+";name=Repeater");

conn = notifier.acceptAndOpen();

senderName = RemoteDevice.getRemoteDevice(conn).getBluetoothAddress();

doInquiry();

uuidSet = new UUID[1];

uuidSet[0] = new UUID(Client.UUID_STRING, false);

ServiceDiscoverer serviceDiscoverer = new ServiceDiscoverer(null, this, null, null);

discoveryAgent.searchServices(null, uuidSet, RemoteDevice.getRemoteDevice(conn), serviceDiscoverer);

RepeaterToSendMessage repeaterToSendMessage = new RepeaterToSendMessage(midlet);

}

catch (Exception ex)

{

midlet.doAlert("Exception : "+ex.toString(), midlet.errorTime());

}

}

public void doInquiry()

{

try

{

DeviceDiscoverer deviceDiscoverer = new DeviceDiscoverer(null, this);

repeaterUI.append("Searching for device...");

discoveryAgent.startInquiry(DiscoveryAgent.GIAC, deviceDiscoverer);

}

catch (BluetoothStateException bse)

{

midlet.doAlert("BluetoothStateException : "+bse.toString(), midlet.errorTime());

}

}

public void deviceInquiryFinished(Vector deviceVector, String message)

{

remoteDevice = new RemoteDevice[deviceVector.size()];

repeaterUI.deleteAll();

if (deviceVector.size() == 0)

{

message = "No Device Detected";

}

else

{

for (int i=0; i<deviceVector.size(); i++)

{

remoteDevice = (RemoteDevice)deviceVector.elementAt(i);

}

message = (remoteDevice.length)+" devices have been discovered\n";

}

repeaterUI.append(message);

for (int i=0; i><remoteDevice.length; i++)

{

if (remoteDevice.getBluetoothAddress().equals(senderName))

{}

else

{

repeaterUI.append(remoteDevice.getBluetoothAddress()+"\n");

bluetoothDevices += remoteDevice.getBluetoothAddress()+" ";

}

}

}

public void serviceSearchFinished(String message, String serviceURL)

{

midlet.sendMessage(bluetoothDevices, serviceURL);

}

}>

skylancera at 2007-7-12 10:43:11 > top of Java-index,Java Essentials,Java Programming...
# 5

import javax.bluetooth.BluetoothStateException;

import javax.bluetooth.DiscoveryAgent;

import javax.bluetooth.LocalDevice;

import javax.bluetooth.RemoteDevice;

import javax.bluetooth.UUID;

import javax.microedition.io.Connector;

import javax.microedition.io.StreamConnection;

import javax.microedition.io.StreamConnectionNotifier;

import javax.microedition.lcdui.Command;

import javax.microedition.lcdui.CommandListener;

import javax.microedition.lcdui.Displayable;

import javax.microedition.lcdui.Form;

class RepeaterToSendMessage implements CommandListener

{

public static final String UUID_STRING = "B1B2B3B4B5B6B7B8B9B0C1C2C3C4C5C6";

private String bluetoothReceiver = "";

private String bluetoothSender = "";

private String text = "";

private String code = "";

private BlueReplicationMIDlet midlet = null;

private ServiceDiscoverer serviceDiscoverer = null;

private LocalDevice localDevice = null;

private DiscoveryAgent discoveryAgent = null;

private UUID[] uuidSet = null;

private StreamConnection conn = null;

private Command exitCommand = new Command("Exit", Command.EXIT, 1);

private Form repeaterToSendMessageUI = new Form("Repeater To Send Message UI");

public RepeaterToSendMessage(BlueReplicationMIDlet midlet)

{

this.midlet = midlet;

midlet.getDisplayUI().setCurrent(repeaterToSendMessageUI);

repeaterToSendMessageUI.addCommand(exitCommand);

repeaterToSendMessageUI.setCommandListener(this);

try

{

localDevice = LocalDevice.getLocalDevice();

discoveryAgent = localDevice.getDiscoveryAgent();

}

catch (BluetoothStateException bse)

{

midlet.doAlert("BluetoothStateException : "+bse.toString(), midlet.errorTime());

midlet.exit();

}

serviceDiscoverer = new ServiceDiscoverer(null, null, this, null);

sendMessage();

}

public void commandAction(Command c, Displayable d)

{

if (c == exitCommand)

{

midlet.exit();

}

}

public void sendMessage()

{

new Thread()

{

public void run()

{

try

{

StreamConnectionNotifier notifier = (StreamConnectionNotifier)Connector.open("btspp://localhost:"+UUID_STRING+";name=RepeaterToSendMessage");

conn = notifier.acceptAndOpen();

String message = midlet.readMessage(conn);

code = midlet.getCode(message);

bluetoothReceiver = midlet.getBluetoothReceiver(message);

bluetoothSender = RemoteDevice.getRemoteDevice(conn).getBluetoothAddress();

text = midlet.getMessage(message);

uuidSet = new UUID[1];

if (code.equals("1"))

{

uuidSet[0] = new UUID(Client.UUID_STRING, false);

System.out.println("Pesan dikirim dari server ke client");

repeaterToSendMessageUI.append("Pesan dikirim dari server ke client");

}

else if (code.equals("2"))

{

uuidSet[0] = new UUID(Server.UUID_STRING, false);

System.out.println("Pesan dikirim dari client ke server");

repeaterToSendMessageUI.append("Pesan dikirim dari client ke server");

}

discoveryAgent.searchServices(null, uuidSet, midlet.makeRemoteDevice(bluetoothReceiver), serviceDiscoverer);

new Thread()

{

public void run()

{

sendMessage();

}

}.start();

}

catch (Exception ex)

{

midlet.doAlert("Exception : "+ex.toString(), midlet.errorTime());

}

}

}.start();

}

public void serviceSearchFinished(String message, String serviceURL)

{

midlet.sendMessage(" - "+bluetoothSender+" = "+text, serviceURL);

}

}

skylancera at 2007-7-12 10:43:11 > top of Java-index,Java Essentials,Java Programming...
# 6

import java.io.OutputStream;

import javax.bluetooth.BluetoothStateException;

import javax.bluetooth.DiscoveryAgent;

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;

import javax.microedition.io.StreamConnectionNotifier;

import javax.microedition.lcdui.Command;

import javax.microedition.lcdui.CommandListener;

import javax.microedition.lcdui.Displayable;

import javax.microedition.lcdui.Form;

import javax.microedition.lcdui.TextField;

class Server implements CommandListener

{

public static final String UUID_STRING = "123456789ABCDEF";

private String bluetoothReceiver = "";

private BlueReplicationMIDlet midlet = null;

private LocalDevice localDevice = null;

private DiscoveryAgent discoveryAgent = null;

private UUID[] uuidSet = null;

private StreamConnection conn = null;

private Form mainUI = new Form("Server UI");

private Command exitCommand = new Command("Exit", Command.EXIT, 1);

private Command sendCommand = new Command("Send", Command.SCREEN, 1);

private TextField incoming = new TextField("Incoming", "", 256, TextField.UNEDITABLE);

private TextField outgoing = new TextField("Outgoing", "", 256, TextField.ANY);

public Server(BlueReplicationMIDlet midlet)

{

this.midlet = midlet;

midlet.getDisplayUI().setCurrent(mainUI);

mainUI.append(incoming);

mainUI.append(outgoing);

mainUI.addCommand(exitCommand);

mainUI.addCommand(sendCommand);

mainUI.setCommandListener(this);

uuidSet = new UUID[1];

try

{

localDevice = LocalDevice.getLocalDevice();

discoveryAgent = localDevice.getDiscoveryAgent();

}

catch (BluetoothStateException bse)

{

midlet.doAlert("BluetoothStateException : "+bse.toString(), midlet.errorTime());

midlet.exit();

}

mainUI.append("My Name : "+localDevice.getBluetoothAddress());

new Thread()

{

public void run()

{

startServer();

}

}.start();

}

public void commandAction(Command c, Displayable d)

{

if (c == exitCommand)

{

midlet.exit();

}

else if (c == sendCommand)

{

final ServiceDiscoverer serviceDiscoverer = new ServiceDiscoverer(null, null, null, this);

new Thread()

{

public void run()

{

uuidSet[0] = new UUID(RepeaterToSendMessage.UUID_STRING, false);

try

{

discoveryAgent.searchServices(null, uuidSet, RemoteDevice.getRemoteDevice(conn), serviceDiscoverer);

StreamConnectionNotifier notifier = (StreamConnectionNotifier)Connector.open("btspp://localhost:"+UUID_STRING+";name=Server");

conn = notifier.acceptAndOpen();

outgoing.setString(midlet.readMessage(conn));

}

catch (Exception ex)

{

midlet.doAlert("Exception : "+ex.toString(), midlet.errorTime());

}

}

}.start();

}

}

public void startServer()

{

try

{

localDevice.setDiscoverable(DiscoveryAgent.GIAC);

StreamConnectionNotifier notifier = (StreamConnectionNotifier)Connector.open("btspp://localhost:"+UUID_STRING+";name=StartServer");

ServiceRecord record = localDevice.getRecord(notifier);

String connURL = record.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);

conn = notifier.acceptAndOpen();//record is saved to the SDDB on this call

new Thread()

{

public void run()

{

startReceiver();

}

}.start();

}

catch (Exception ex)

{

midlet.doAlert("Exception : "+ex.toString(), midlet.errorTime());

}

}

public void startReceiver()

{

String text = midlet.readMessage(conn);

bluetoothReceiver = midlet.getBluetoothReceiver(text);

incoming.setString(midlet.getMessage(text));

}

public void serviceSearchFinished(String message, String serviceURL)

{

try

{

System.out.println("test1");

//the problem : connector didn't want to open the service, why? please help me?

StreamConnection conn2 = (StreamConnection)Connector.open(serviceURL);

System.out.println("test2");

OutputStream out = conn2.openOutputStream();

out.write(("1 - "+bluetoothReceiver+" = "+outgoing.getString()).getBytes());

out.close();

conn2.close();

}

catch (Exception ex)

{

midlet.doAlert("Exception : "+ex.toString(), midlet.errorTime());

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

}

//midlet.sendMessage("1 - "+bluetoothReceiver+" = "+outgoing.getString(), serviceURL);

}

}

Message was edited by:

skylancer

skylancera at 2007-7-12 10:43:11 > top of Java-index,Java Essentials,Java Programming...
# 7

import javax.bluetooth.DataElement;

import javax.bluetooth.DeviceClass;

import javax.bluetooth.DiscoveryListener;

import javax.bluetooth.RemoteDevice;

import javax.bluetooth.ServiceRecord;

class ServiceDiscoverer implements DiscoveryListener

{

private static final String SERVICE_NAME = "L2CAPchat";

private String serviceUrl = "";

private ServiceRecord serviceRecord = null;

private BlueReplicationMIDlet midlet = null;

private Client client = null;

private Repeater repeater = null;

private RepeaterToSendMessage repeaterToSendMessage = null;

private Server server = null;

public ServiceDiscoverer(BlueReplicationMIDlet midlet)

{

this.midlet = midlet;

}

public ServiceDiscoverer(Client clie, Repeater rep, RepeaterToSendMessage repMsg, Server serv)

{

if (clie != null)

this.client = clie;

else if (rep != null)

this.repeater = rep;

else if (repMsg != null)

this.repeaterToSendMessage = repMsg;

else if (serv != null)

this.server = serv;

}

public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass deviceClass)

{}

public void inquiryCompleted(int discType)

{}

public void servicesDiscovered(int transID, ServiceRecord[] servRecord)

{

if (midlet != null)

{

for (int i=0; i<servRecord.length; i++)

{

DataElement serviceNameElement = servRecord[i].getAttributeValue(0x100);//get the Service Name

String serviceName = (String)serviceNameElement.getValue();

if (serviceName.equals(SERVICE_NAME))

{

serviceRecord = servRecord[0];

}

}

}

else

{

for (int i=0; i><servRecord.length; i++)

{

serviceUrl = servRecord[i].getConnectionURL(0, false);

}

}

}

public void serviceSearchCompleted(int transID, int responseCode)

{

String message = null;

if (responseCode == SERVICE_SEARCH_ERROR)

message = "SERVICE_SEARCH_ERROR";

if (responseCode == SERVICE_SEARCH_COMPLETED)

message = "SERVICE_SEARCH_COMPLETED\nService URL: "+serviceUrl;

if (responseCode == SERVICE_SEARCH_TERMINATED)

message = "SERVICE_SEARCH_TERMINATED";

if (responseCode == SERVICE_SEARCH_NO_RECORDS)

message = "SERVICE_SEARCH_NO_RECORDS ";

if (responseCode == SERVICE_SEARCH_DEVICE_NOT_REACHABLE)

message = "SERVICE_SEARCH_DEVICE_NOT_REACHABLE ";

if (midlet != null)

{

midlet.serviceSearchFinished(serviceRecord, message);

midlet = null;

serviceRecord = null;

}

else if (client != null)

{

client.serviceSearchFinished(message, serviceUrl);

client = null;

}

else if (repeater != null)

{

repeater.serviceSearchFinished(message, serviceUrl);

repeater = null;

}

else if (repeaterToSendMessage != null)

{

repeaterToSendMessage.serviceSearchFinished(message, serviceUrl);

repeaterToSendMessage = null;

}

else if (server != null)

{

server.serviceSearchFinished(message, serviceUrl);

server = null;

}

}

}

Message was edited by:

skylancer>

skylancera at 2007-7-12 10:43:11 > top of Java-index,Java Essentials,Java Programming...
# 8

FFS, didn't the fact that the first mess of code not give you a hint that perhaps you were missing something.

[url=http://forum.java.sun.com/help.jspa?sec=formatting]Use Code tags when posting code[/url]

Please go back over each post (assuming you didn't reply to any of them), and edit them to use the code tags. Just select the code, and click on the code button.

Of course better still would have been for you to put the effort in, and produce an [url=http://mindprod.com/jgloss/sscce.html]SSCCE[/url]. That way, you would either solve the problem, or at least narrow it down to a few lines of code that we could help you with.

macrules2a at 2007-7-12 10:43:11 > top of Java-index,Java Essentials,Java Programming...
# 9
ok, thanks for your advicebut some code couldn't be edittedbut i'll edit soonand, what is SSCE?
skylancera at 2007-7-12 10:43:11 > top of Java-index,Java Essentials,Java Programming...
# 10
Click on the link.
macrules2a at 2007-7-12 10:43:11 > top of Java-index,Java Essentials,Java Programming...