Exemplo do Marge
Servidor
Bibliotecas:
marge-core-0.5.jar
bluecove-2.0.3.jar
/*
* Marge, Java Bluetooth Framework
* Copyright (C) 2006 Project Marge
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* [email removido]
* http://marge.dev.java.net
*/
package net.java.dev.marge.bluechatjm;
import java.io.IOException;
import javax.bluetooth.RemoteDevice;
import net.java.dev.marge.communication.CommunicationListener;
import net.java.dev.marge.communication.ConnectionListener;
import net.java.dev.marge.entity.Device;
import net.java.dev.marge.entity.ServerDevice;
import net.java.dev.marge.entity.config.ServerConfiguration;
import net.java.dev.marge.factory.CommunicationFactory;
import net.java.dev.marge.factory.RFCOMMCommunicationFactory;
public class BluechatRFCOMMEchoServer implements CommunicationListener, ConnectionListener {
private CommunicationFactory communicationFactory;
private Device device;
public BluechatRFCOMMEchoServer(CommunicationFactory communicationFactory) {
this.communicationFactory = communicationFactory;
}
public void startServer() {
ServerConfiguration config = new ServerConfiguration(this);
config.setMaxNumberOfConnections(5);
communicationFactory.waitClients(config, this);
}
public void errorOnConnection(IOException e) {
System.err.println(e.getMessage());
}
public void connectionEstablished(ServerDevice device, RemoteDevice remote) {
System.out.println(remote.getBluetoothAddress());
this.device = device;
device.startListening();
device.setEnableBroadcast(true);
}
public void receiveMessage(byte[] receivedString) {
String s = new String(receivedString);
System.out.println("Recebido:"+s);
device.send(("echo: " + s).getBytes());
System.out.println("Echo enviado...");
}
public void errorOnReceiving(IOException e) {
System.err.println(e.getMessage());
}
public void errorOnSending(IOException e) {
System.err.println(e.getMessage());
}
public static void main(String[] args) {
BluechatRFCOMMEchoServer server = new BluechatRFCOMMEchoServer(new RFCOMMCommunicationFactory());
System.out.println("Recebendo conexão dos usuários:");
server.startServer();
}
}
Exemplo do Marge
Cliente - são vários arquivos
Bibliotecas:
marge-core-0.5.jar
BlueChatMIDlet.java
/*
* Marge, Java Bluetooth Framework
* Copyright (C) 2006 Project Marge
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* [email removido]
* http://marge.dev.java.net
*/
package net.java.dev.marge.bluechatjm;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import net.java.dev.marge.entity.Device;
public class BlueChatMIDlet extends MIDlet {
private static BlueChatMIDlet instance;
private Display display;
private Device device;
private MainMenu mainMenu;
public BlueChatMIDlet() {
display = Display.getDisplay(this);
instance = this;
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
notifyDestroyed();
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
setCurrent(this.mainMenu = new MainMenu());
}
public void exit() {
try {
this.destroyApp(true);
} catch (MIDletStateChangeException e) {
e.printStackTrace();
}
}
public void setCurrent(Displayable d) {
this.display.setCurrent(d);
}
public void setCurrent(Alert a, Displayable d) {
this.display.setCurrent(a, d);
}
public Device getDevice() {
return device;
}
public void setDevice(Device device) {
this.device = device;
}
public void showError(String message, Displayable d) {
Alert alert = new Alert("Erro", message, null, AlertType.ERROR);
alert.setTimeout(2000);
display.setCurrent(alert, d);
}
public static BlueChatMIDlet getInstance() {
return instance;
}
public void showMainMenu() {
this.setCurrent(this.mainMenu);
}
}
ChatForm,java
/*
* Marge, Java Bluetooth Framework
* Copyright (C) 2006 Project Marge
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* [email removido]
* http://marge.dev.java.net
*/
package net.java.dev.marge.bluechatjm;
import java.io.IOException;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import net.java.dev.marge.communication.CommunicationListener;
import net.java.dev.marge.entity.Device;
public class ChatForm extends Form implements CommunicationListener,
CommandListener {
private Device device;
private Command back;
private TextField chatField;
public ChatForm() {
super("Chat...");
this.chatField = new TextField("Mensagem", null, 100, TextField.ANY);
this.append(this.chatField);
this.addCommand(new Command("Enviar", Command.OK, 1));
this.addCommand(this.back = new Command("Voltar", Command.BACK, 1));
this.setCommandListener(this);
}
public void receiveMessage(byte[] receivedString) {
this.insert(1, new StringItem("Recebido: ", new String(receivedString)));
}
public void errorOnReceiving(IOException e) {
e.printStackTrace();
this.leaveChat();
}
public void errorOnSending(IOException e) {
e.printStackTrace();
this.leaveChat();
}
public void sendMessage(String message) {
this.device.send(message.getBytes());
this.insert(1, new StringItem("Enviado: ", message));
}
public void setDevice(Device device) {
this.device = device;
}
public void leaveChat() {
this.deleteAll();
this.append(this.chatField);
this.device.close();
BlueChatMIDlet.getInstance().showMainMenu();
}
public void commandAction(Command c, Displayable d) {
if (c == this.back) {
this.leaveChat();
} else {
this.sendMessage(this.chatField.getString());
}
}
}
InquiryList.java
/*
* Marge, Java Bluetooth Framework
* Copyright (C) 2006 Project Marge
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* [email removido]
* http://marge.dev.java.net
*/
package net.java.dev.marge.bluechatjm;
import java.io.IOException;
import java.util.Vector;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import net.java.dev.marge.entity.ClientDevice;
import net.java.dev.marge.entity.config.ClientConfiguration;
import net.java.dev.marge.factory.CommunicationFactory;
import net.java.dev.marge.inquiry.DeviceDiscoverer;
import net.java.dev.marge.inquiry.InquiryListener;
import net.java.dev.marge.inquiry.ServiceDiscoverer;
import net.java.dev.marge.inquiry.ServiceSearchListener;
public class InquiryList extends List implements CommandListener,
ServiceSearchListener, InquiryListener {
private MainMenu mainMenu;
private Command select;
private Command stopOrBack;
private Vector devices;
private CommunicationFactory factory;
public InquiryList(MainMenu menu, CommunicationFactory factory) {
super("Buscando...", List.IMPLICIT);
this.select = null;
this.mainMenu = menu;
this.factory = factory;
this.devices = new Vector(5);
this.addCommand(this.stopOrBack = new Command("Parar",
Command.CANCEL, 1));
this.setCommandListener(this);
new Thread() {
public void run() {
try {
DeviceDiscoverer.getInstance().startInquiryGIAC(InquiryList.this);
} catch (BluetoothStateException e) {
e.printStackTrace();
}
}
}.start();
}
public void commandAction(Command c, Displayable d) {
if (c == this.stopOrBack) {
if (c.getCommandType() == Command.CANCEL) {
try {
DeviceDiscoverer.getInstance().cancelInquiry();
this.removeCommand(c);
this.stopOrBack = new Command("Voltar", Command.BACK, 1);
this.addCommand(this.stopOrBack);
} catch (BluetoothStateException ex) {
ex.printStackTrace();
}
} else {
BlueChatMIDlet.getInstance().showMainMenu();
}
} else {
if (this.select != null) {
try {
DeviceDiscoverer.getInstance().cancelInquiry();
ServiceDiscoverer.getInstance().startSearch((RemoteDevice) this.devices.elementAt(this.getSelectedIndex()), this);
} catch (BluetoothStateException e) {
e.printStackTrace();
}
}
}
}
public void deviceNotReachable() {
BlueChatMIDlet.getInstance().setCurrent(new Alert("Info", "Device not reachable", null, AlertType.INFO), this);
}
public void serviceSearchCompleted(RemoteDevice remoteDevice,
ServiceRecord[] services) {
try {
ClientConfiguration config = new ClientConfiguration(services[0],
this.mainMenu.getChatForm());
ClientDevice clientDevice = this.factory.connectToServer(config);
this.mainMenu.changeToChatScreen(clientDevice);
} catch (IOException e) {
this.mainMenu.errorOnConnection(e);
}
}
public void serviceSearchError() {
BlueChatMIDlet.getInstance().setCurrent(new Alert("Error", "Service search error", null, AlertType.ERROR), this);
}
public void deviceDiscovered(RemoteDevice device, DeviceClass deviceClass) {
if (this.select == null) {
this.select = new Command("Selec", Command.OK, 1);
this.addCommand(select);
}
this.devices.addElement(device);
this.setTitle("Buscando... " + this.devices.size());
try {
this.append(device.getFriendlyName(false), null);
} catch (IOException e) {
this.append(device.getBluetoothAddress(), null);
e.printStackTrace();
}
}
public void inquiryCompleted(RemoteDevice[] devices) {
this.setTitle(Integer.toString(this.devices.size()) + " encontrados");
this.removeCommand(this.stopOrBack);
this.stopOrBack = new Command("Voltar", Command.BACK, 1);
this.addCommand(this.stopOrBack);
}
public void inquiryError() {
BlueChatMIDlet.getInstance().setCurrent(new Alert("Error", "Inquiry error", null, AlertType.ERROR), this);
}
}
LoadingScreen.java
/*
* Marge, Java Bluetooth Framework
* Copyright (C) 2006 Project Marge
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* [email removido]
* http://marge.dev.java.net
*/
package net.java.dev.marge.bluechatjm;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;
public class LoadingScreen extends Form implements CommandListener {
private MainMenu menu;
public LoadingScreen(MainMenu menu) {
super("Esperando...");
this.menu = menu;
this.append(new Gauge("Esperando conexões", false, Gauge.INDEFINITE, Gauge.CONTINUOUS_RUNNING));
this.addCommand(new Command("Cancelar", Command.CANCEL, 1));
this.setCommandListener(this);
}
public void commandAction(Command arg0, Displayable arg1) {
this.menu.setCancelled();
BlueChatMIDlet.getInstance().showMainMenu();
}
}
MainMenu.java
/*
* Marge, Java Bluetooth Framework
* Copyright (C) 2006 Project Marge
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* [email removido]
* http://marge.dev.java.net
*/
package net.java.dev.marge.bluechatjm;
import java.io.IOException;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import net.java.dev.marge.communication.ConnectionListener;
import net.java.dev.marge.entity.ClientDevice;
import net.java.dev.marge.entity.ServerDevice;
import net.java.dev.marge.entity.config.ServerConfiguration;
import net.java.dev.marge.factory.CommunicationFactory;
import net.java.dev.marge.factory.L2CAPCommunicationFactory;
import net.java.dev.marge.factory.RFCOMMCommunicationFactory;
public class MainMenu extends List implements ConnectionListener, CommandListener {
private final String SELEC_COMMAND_NAME = "Selec";
private ChatForm chatForm;
private boolean cancelled;
public MainMenu() {
super("BlueChat", List.IMPLICIT);
this.append("Cliente", null);
this.append("Servidor", null);
this.append("Sair", null);
this.addCommand(new Command(SELEC_COMMAND_NAME, Command.OK, 1));
this.setCommandListener(this);
this.chatForm = new ChatForm();
this.cancelled = false;
}
public void commandAction(Command c, Displayable d) {
try {
LocalDevice.getLocalDevice().setDiscoverable(DiscoveryAgent.GIAC);
switch (this.getSelectedIndex()) {
case 0:
this.performInquiry(new RFCOMMCommunicationFactory());
break;
case 1:
this.cancelled = false;
this.startServer();
break;
default:
BlueChatMIDlet.getInstance().exit();
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void performInquiry(CommunicationFactory factory) {
BlueChatMIDlet.getInstance().setCurrent(new InquiryList(this, factory));
}
private void startServer() {
BlueChatMIDlet.getInstance().setCurrent(new LoadingScreen(this));
ServerConfiguration config = new ServerConfiguration(chatForm);
config.setMaxNumberOfConnections(7);
CommunicationFactory communicationFactory = new RFCOMMCommunicationFactory();
communicationFactory.waitClients(config, this);
}
public ChatForm getChatForm() {
return chatForm;
}
public void errorOnConnection(IOException exception) {
BlueChatMIDlet.getInstance().showError(exception.getMessage(), this);
}
public void changeToChatScreen(ClientDevice device) {
if (!this.cancelled) {
device.startListening();
this.chatForm.setDevice(device);
BlueChatMIDlet.getInstance().setCurrent(this.chatForm);
}
}
public void connectionEstablished(ServerDevice device, RemoteDevice remote) {
if (!this.cancelled) {
device.startListening();
device.setEnableBroadcast(true);
this.chatForm.setDevice(device);
BlueChatMIDlet.getInstance().setCurrent(this.chatForm);
}
}
public void setCancelled() {
this.cancelled = true;
}
}