RFCOMMServer: import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import javax.bluetooth.BluetoothStateException; import javax.bluetooth.DiscoveryAgent; import javax.bluetooth.ServiceRecord; import javax.bluetooth.LocalDevice; import javax.microedition.io.Connector; import javax.microedition.io.StreamConnectionNotifier; import javax.microedition.io.StreamConnection; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Form; import javax.microedition.lcdui.TextField; import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; public class RFCOMMServer extends MIDlet implements Runnable, CommandListener { private Display display = null; private Form form = new Form("BT-RFCOMM Chat Show/SERVER"); private TextField tfData = new TextField("请输入发送的消息", "", 255, TextField.ANY); private Command cmdExit = new Command("Exit", Command.EXIT, 0); private Command cmdSend = new Command("Send", Command.SCREEN, 1); private boolean isRunning = true; ServiceRecord record = null; StreamConnectionNotifier server = null; private DataInputStream dis = null; private DataOutputStream dos = null; public RFCOMMServer() { super(); form.append(tfData); form.addCommand(cmdExit); form.addCommand(cmdSend); form.setCommandListener(this); } protected void destroyApp(boolean arg0) throws MIDletStateChangeException { // TODO Auto-generated method stub isRunning = false; close(); } protected void pauseApp() { // TODO Auto-generated method stub isRunning = false; close(); } protected void startApp() throws MIDletStateChangeException { // TODO Auto-generated method stub display = Display.getDisplay(this); display.setCurrent(form); new Thread(this).start(); } public void commandAction(Command c, Displayable d) { if (c == cmdExit) { isRunning = false; notifyDestroyed(); } else if (c == cmdSend) { // 发送数据 new Thread() { public void run() { if (dos == null) { return; } String str = tfData.getString(); try { dos.writeUTF(str); dos.flush(); } catch (IOException e) { e.printStackTrace(); } // 显示发送的消息 form.append("[S]" + str + "/n"); } }.start(); } } public void run() { isRunning = true; try { LocalDevice local = LocalDevice.getLocalDevice(); local.setDiscoverable(DiscoveryAgent.GIAC); } catch (BluetoothStateException e) { System.out.println("开始服务失败"); e.printStackTrace(); return; } try { server = (StreamConnectionNotifier) Connector .open("btspp://localhost:11223344556677889900AABBCCDDEEFF"); } catch (IOException e) { System.out.println("开始服务失败 IOException"); e.printStackTrace(); return; } String message = ""; while (isRunning) { StreamConnection conn = null; try { try { conn = server.acceptAndOpen(); } catch (IOException e) { System.err.println("IOException: " + e.getMessage()); return; } dis = conn.openDataInputStream(); dos = conn.openDataOutputStream(); while (isRunning) { message = dis.readUTF(); form.append("[R] " + message + "/n"); Thread.sleep(1000); } } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); conn = null; } catch (Exception e) { e.printStackTrace(); } } } } } public void close() { try { if (dis != null) { dis.close(); dis = null; } if (dos != null) { dos.close(); dos = null; } if (server != null) { server.close(); server = null; } } catch (Exception e) { e.printStackTrace(); } } } RFCOMMClient: import javax.bluetooth.ServiceRecord; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import javax.microedition.io.Connector; import javax.microedition.io.StreamConnection; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.TextField; import javax.microedition.lcdui.Form; import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; public class RFCOMMClient extends MIDlet implements Runnable, CommandListener { private Display display = null; private Form form = new Form("BT-RFCOMM Chat Show/CLIENT"); private TextField tfData = new TextField("请输入发送的消息", "", 255, TextField.ANY); private Command cmdExit = new Command("Exit", Command.EXIT, 0); private Command cmdSend = new Command("Send", Command.SCREEN, 1); private Command cmdConnect = new Command("Connect", Command.SCREEN, 1); private boolean isRunning = true; StreamConnection client = null; ServiceRecord record = null; private DataInputStream dis = null; private DataOutputStream dos = null; // private int count = 0; public RFCOMMClient() { // TODO Auto-generated constructor stub super(); form.append(tfData); form.addCommand(cmdExit); form.addCommand(cmdConnect); form.setCommandListener(this); } protected void destroyApp(boolean arg0) throws MIDletStateChangeException { // TODO Auto-generated method stub isRunning = false; close(); } protected void pauseApp() { // TODO Auto-generated method stub isRunning = false; close(); } protected void startApp() throws MIDletStateChangeException { // TODO Auto-generated method stub display = Display.getDisplay(this); display.setCurrent(form); } public void commandAction(Command c, Displayable d) { if (c == cmdExit) { isRunning = false; notifyDestroyed(); } else if (c == cmdSend) { new Thread() { public void run() { if (dos == null) { return; } String str = tfData.getString(); try { dos.writeUTF(str); dos.flush(); } catch (IOException e) { e.printStackTrace(); } form.append("[S]" + str + "/n"); } }.start(); } else if (c == cmdConnect) { new Thread(this).start(); } } public void run() { isRunning = true; MyDiscoveryListener md = new MyDiscoveryListener(); System.out.println("开始查找服务器"); record = md.searchRemoteDevice(); if (record == null) { return; } StreamConnection con = null; // 获得连接字符串 String conURL = record.getConnectionURL( ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false); form.append("连接字符串" + conURL); System.out.println("连接字符串" + conURL); try { con = (StreamConnection) Connector.open(conURL); form.append("连接到服务器"); System.out.println("连接到服务器"); dis = con.openDataInputStream(); dos = con.openDataOutputStream(); form.removeCommand(cmdConnect); form.addCommand(cmdSend); } catch (Exception e) { e.printStackTrace(); return; } while (isRunning) { try { String message = dis.readUTF(); form.append("[S]" + message + "/n"); Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } } close(); form.removeCommand(cmdSend); form.addCommand(cmdConnect); } public void close() { try { if (dis != null) { dis.close(); dis = null; } if (dos != null) { dos.close(); dos = null; } if (client != null) { client.close(); client = null; } } catch (Exception e) { e.printStackTrace(); } } } MyDiscoveryListener: import java.util.Vector; import javax.bluetooth.BluetoothStateException; 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; public class MyDiscoveryListener implements DiscoveryListener { Vector devices = new Vector(); private DiscoveryAgent agent; UUID[] searchList = { new UUID("11223344556677889900AABBCCDDEEFF", false) }; private ServiceRecord record; ServiceRecord searchRemoteDevice() { LocalDevice ld = null; try { ld = LocalDevice.getLocalDevice(); } catch (BluetoothStateException e) { e.printStackTrace(); return null; } agent = ld.getDiscoveryAgent(); // 从缓冲中查找 RemoteDevice[] devList = agent.retrieveDevices(DiscoveryAgent.CACHED); if (devList != null) { if (searchServices(devList)) { return record; } } devList = agent.retrieveDevices(DiscoveryAgent.PREKNOWN); if (devList != null) { if (searchServices(devList)) { return record; } } // 若缓冲和pre-known中没有设备,则搜索所有的设备 try { agent.startInquiry(DiscoveryAgent.GIAC, this); // 等待所有设备被发现后再继续搜索服务 synchronized (this) { try { this.wait(); } catch (Exception e) { e.printStackTrace(); } } } catch (BluetoothStateException e) { System.out.println("不能发现设备: " + e); } if (devices.size() > 0) { devList = new RemoteDevice[devices.size()]; devices.copyInto(devList); if (searchServices(devList)) { return record; } } return null; } boolean searchServices(RemoteDevice[] devList) { for (int i = 0; i < devList.length; i++) { try { System.out.println("/n开始搜索" + devList[i].getBluetoothAddress() + "上的服务"); agent.searchServices(null, searchList, devList[i], this); } catch (BluetoothStateException e) { System.out.println("BtStateEx " + e.getMessage()); } // 一次执行一个搜索 synchronized (this) { try { this.wait(); } catch (Exception e) { e.printStackTrace(); } } // 一旦发现设备就退出搜索 if (record != null) { System.out.println("发现服务器"); return true; } } return false; } public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) { System.out.println("发现设备" + btDevice.getBluetoothAddress()); devices.addElement(btDevice); } public void inquiryCompleted(int arg0) { // TODO Auto-generated method stub System.out.println("设备查询完毕"); System.out.println("共发现设备 " + devices.size()); // 查询结束后通知searchRemoteDevice继续执行 synchronized (this) { try { this.notifyAll(); } catch (Exception e) { e.printStackTrace(); } } } public void serviceSearchCompleted(int arg0, int arg1) { // TODO Auto-generated method stub System.out.println("服务查询完毕"); synchronized (this) { this.notifyAll(); } } public void servicesDiscovered(int arg0, ServiceRecord[] servRecord) { // TODO Auto-generated method stub // 保存服务 record = servRecord[0]; synchronized (this) { this.notifyAll(); } } }