import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Hashtable;
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;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.TextBox;
public class GameClient implements DiscoveryListener, CommandListener, Runnable {
private GameUI gameUI;
private DiscoveryAgent discoveryAgent;
private RemoteDevice remoteDevice;
private ServiceRecord serviceRecord;
private String url;
private boolean searchFinished = false;
private boolean serviceFinished = false;
private Alert alert;
// private final String uuidString = "F0E0D0C0B0A000908070605040302010";
private OutputStream outputStream;
private InputStream inputStream;
private StreamConnection streamConnection;
Hashtable remoteDevices = new Hashtable();
Hashtable services = new Hashtable();
Vector vURL = new Vector();
Vector vName = new Vector();
private String cmd;
public GameClient(GameUI gameUI) {
this.gameUI = gameUI;
alert = new Alert("错误");
alert.setTimeout(Alert.FOREVER);
alert.addCommand(new Command("返回", Command.ITEM, 1));
alert.setCommandListener(this);
try {
LocalDevice localDevice = LocalDevice.getLocalDevice();
localDevice.setDiscoverable(DiscoveryAgent.GIAC);
discoveryAgent = localDevice.getDiscoveryAgent();
} catch (Exception e) {
showError(e.getMessage());
}
}
public void search() {
searchFinished = false;
this.remoteDevices.clear();
this.services.clear();
this.vURL.removeAllElements();
this.vName.removeAllElements();
try {
this.discoveryAgent.startInquiry(DiscoveryAgent.GIAC, this); // 开始搜索设备
} catch (BluetoothStateException e) {
showError(e.getMessage());
}
}
public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass arg1) {
String name = "";
try {
name = remoteDevice.getFriendlyName(false);
} catch (IOException e2) {
name = remoteDevice.getBluetoothAddress();
}
this.remoteDevices.put(name, remoteDevice);
this.vName.addElement(name);
}
public void inquiryCompleted(int discType) {
/*
* try { this.searchServices(this.remoteDevices); } catch (Exception e)
* { showError(e.getMessage()); } remoteDevices.clear();
*/
if (discType == DiscoveryListener.INQUIRY_COMPLETED) {
searchFinished = true;
synchronized (this) {
notifyAll();
}
} else if (discType == DiscoveryListener.INQUIRY_TERMINATED) {
showError("搜索蓝牙设备异常终止!");
} else if (discType == DiscoveryListener.INQUIRY_ERROR) {
showError("搜索蓝牙设备出错!");
}
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
/*
* try { if (servRecord == null || servRecord.length == 0) { url = null;
* this.serviceRecord = null; return; }
*
* this.serviceRecord = servRecord[0]; url =
* this.serviceRecord.getConnectionURL(
* ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false); vURL.addElement(url);
* vName.addElement(this.remoteDevice.getFriendlyName(false));
* services.put(this.remoteDevice.getFriendlyName(false), this.url); }
* catch (Exception e) { showError(e.getMessage()); }
*/
try {
if (servRecord.length > -1) {
for (int j = 0; j <= servRecord.length - 1; j++) {
String tmpURL = servRecord[j].getConnectionURL(
ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);// 读出的设备服务连接地址
gameUI.clientUI.setTitle("搜索到服务..." + tmpURL);
if (tmpURL != null) {
url = tmpURL;
}
}
}
} catch (Exception e) {
showError(e.getMessage());
}
}
public void serviceSearchCompleted(int i, int j) {
if (j != 1) {
showError("没有搜索到任何可用服务");
}
serviceFinished = true;
synchronized(this) {
notifyAll();
}
}
// private void searchServices(Hashtable remotes)
// throws BluetoothStateException {
// UUID[] UUIDs = new UUID[2];
// UUIDs[1] = new UUID(this.uuidString, false);
// UUIDs[0] = new UUID(0x0003);
// for (Enumeration e = remotes.keys(); e.hasMoreElements();) {
// String key = (String) e.nextElement();
// remoteDevice = (RemoteDevice) remotes.get(key);
// this.discoveryAgent.searchServices(null, UUIDs, remoteDevice, this);
// }
// }
public void sendCmd(String cmd, String selectedDevice) {
gameUI.clientUI.setTitle("搜索服务...");
this.cmd = cmd;
this.serviceFinished = false;
// 搜索蓝牙设备服务,auuid为指定的服务类型,0×1103代表播号网络服务
// UUID auuid[] = { new UUID(0x1103), new UUID(0x0100) };
UUID auuid[] = { new UUID(4355L), new UUID(256L) };
try {
this.discoveryAgent.searchServices(null, auuid,
(RemoteDevice)remoteDevices.get(selectedDevice), this);
} catch (BluetoothStateException e) {
showError(e.getMessage());
}
// 等到服务搜索完毕
while (this.serviceFinished == false) {
}
gameUI.clientUI.setTitle("搜索服务完畢:" + url);
//
// Alert alert = new Alert("url");
// alert.setTimeout(Alert.FOREVER);
// alert.setString(url);
// Display.getDisplay(gameUI.paMidlet).setCurrent(alert);
try {
new Thread(this).start(); // 新建一个线程来启动,因为基于GCF需要一个独立线程
} catch (Exception e) {
showError(e.getMessage());
}
}
public void run() {
try {
streamConnection = (StreamConnection) Connector.open(url);
outputStream = streamConnection.openOutputStream();// 创建输出流
inputStream = streamConnection.openInputStream();// 创建输入流
// outputStream.write("AT+CMGF=0".getBytes());
// //设置信息格式,0为TEXT方式和1为PDU方式。
// outputStream.write("AT+CMGS='13160091551',10".getBytes());
// //发送短信到XX
// outputStream.write("0x600xa80x590x7d0x000x1a".getBytes());//发送中文短信内容
outputStream.write(cmd.getBytes()); // 读取电话簿
outputStream.write(13);
outputStream.write(10);
outputStream.flush();
new Thread(new Read()).start();
} catch (Exception e) {
showError(e.getMessage());
}
}
public Enumeration getRemoteName() {
while (this.searchFinished == false) {} // 阻塞
return this.vName.elements();
}
public void commandAction(Command c, Displayable d) {
this.gameUI.paMidlet.mainform();
}
public void showError(String msg) {
alert.setString(msg);
Display.getDisplay(gameUI.paMidlet).setCurrent(alert);
}
class Read extends Thread {
public void run(){
try{
gameUI.clientUI.setTitle("接收数据");
List result = new List("结果", List.IMPLICIT);
result.addCommand(new Command("返回", Command.ITEM, 1));
result.setCommandListener(new CommandListener(){
public void commandAction(Command c, Displayable d) {
Display.getDisplay(gameUI.paMidlet).setCurrent(gameUI.clientUI);
}
});
Display.getDisplay(gameUI.paMidlet).setCurrent(result);
String response = "";
int readn = 0;
readn = inputStream.read();
do {
if (readn == -1){
break;
}
String tmpStr = "" + (char) readn;
result.append(tmpStr, null);
response = response + tmpStr;
readn = inputStream.read();
} while(true);
}catch(Exception e){
showError(e.getMessage());
}
}
}
}