📄 session.java
字号:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;
import javax.bluetooth.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
/**
* @author clark
*
*/
public class Session extends TextBox implements Runnable
{
MIDlet midlet;
private boolean isServer;
Server s;
Client c;
public Session( MIDlet midlet )
{
super(null, "准备启动蓝牙设备", 500, TextField.ANY);
this.midlet = midlet;
showInfo("haha");
//setAsServerMode();
}
public void setAsServerMode()
{
isServer = true;
System.out.println("is Server");
}
public void setAsClientMode()
{
isServer = false;
System.out.println("is Client");
}
public boolean initBlueTooch( String serverName )
{
if(isServer)
{
s = new Server(this);
System.out.println("session Server");
}
else
{
c = new Client(this);
System.out.println("session Client");
}
return true;
}
public boolean isConnected()
{
if( isServer )
{
if ( s.isConnected )
{
return true;
}
}
else
{
if ( c.isConnected )
{
return true;
}
}
return false;
}
public StreamConnection getConnections()
{
if (isServer)
{
return s.getConnections();
}
else
{
return c.getConnections();
}
}
public void showInfo(String s)
{
StringBuffer sb = new StringBuffer(this.getString());
if (sb.length() > 0)
{
sb.append("\n");
}
sb.append(s);
this.setString(sb.toString());
}
public void run()
{
// TODO 自动生成方法存根
}
}
class Server implements Runnable, CommandListener
{
public Session session;
public LocalDevice localDevice;
public StreamConnectionNotifier notifier;
public ServiceRecord serviceRecord;
public StreamConnection conn;
boolean isClosed;
boolean isBTReady;
boolean isConnected;
ClientProcessor processor;
public StringBuffer url;
private static UUID ECHO_SERVER_UUID= new UUID("A8D4EDAAC0394FEC9F90283162D1D8D2",false);
/**
* 无参数的Server将使用的UUID是由Session类实现的
* 无认证
* 不加密
*/
public Server(Session session)
{
// TODO 自动生成构造函数存根
this.session = session;
// prepare a URL to create a notifier
url = new StringBuffer("btspp://");
// indicate this is a server
url.append("localhost").append(':');
// add the UUID to identify this service
url.append(ECHO_SERVER_UUID.toString());
// add the name for our service
url.append(";name=Echo Server");
// request all of the client not to be authorized
// some devices fail on authorize=true
url.append(";authorize=false");
isConnected = false;
new Thread(this).start();
System.out.println("end Server run");
}
public void run()
{
// TODO 自动生成方法存根
System.out.println("running server");
isBTReady = false;
try
{
localDevice = LocalDevice.getLocalDevice();
System.out.println("get Device");
if (!localDevice.setDiscoverable(DiscoveryAgent.GIAC))
{
showInfo("无法设置设备发现模式");
return;
}
// create notifier now
System.out.println("eeeeeee");
notifier = (StreamConnectionNotifier) Connector.open(url.toString());
serviceRecord = localDevice.getRecord(notifier);
// remember we've reached this point.
isBTReady = true;
}
catch (Exception e)
{
e.printStackTrace();
}
// nothing to do if no bluetooth available
if (isBTReady)
{
showInfo("初始化成功,等待连接");
}
else
{
showInfo("初始化失败,退出");
return;
}
isClosed = false;
// 生成服务端服务线程对象
//processor = new ClientProcessor();
// ok, start accepting connections then
while (!isClosed)
{
System.out.println("Server is waiting");
//StreamConnection conn = null;
try
{
conn = notifier.acceptAndOpen();
System.out.println("wait.....");
RemoteDevice rd = RemoteDevice.getRemoteDevice(conn);
System.out.println("here the new connectiong is from:"+rd.getFriendlyName(false));
//conn.close();
}
catch (IOException e)
{
// wrong client or interrupted - continue anyway
System.out.println("a err");
continue;
}
//processor.addConnection(conn);
break;
}
isConnected = true;
System.out.println("Server get a new conn");
}
public StreamConnection getConnections()
{
/*
while(true)
{
try
{
conn = notifier.acceptAndOpen();
}
catch (IOException e)
{
// TODO 自动生成 catch 块
e.printStackTrace();
continue;
}
break;
}
*/
System.out.println("得到连接");
return conn;
}
private void showInfo(String s)
{
// StringBuffer sb = new StringBuffer(this.getString());
// if (sb.length() > 0)
// {
// sb.append("\n");
// }
//
// sb.append(s);
// this.setString(sb.toString());
System.out.println(s);
}
public void cancelService()
{
isClosed = true;
showInfo("服务终止");
}
/**
* 处理客户端连接
*
* @param conn
*/
private void processConnection(StreamConnection conn)
{
// 读取输入
String inputString = readInputString(conn);
// 生成响应
String outputString = inputString.toUpperCase();
// 输出响应
sendOutputData(outputString, conn);
try
{
conn.close();
}
catch (IOException e)
{
} // ignore
showInfo("客户端输入:" + inputString + ",已成功响应!");
}
/**
* 从StreamConnection读取输入
*
* @param conn
* @return
*/
private String readInputString(StreamConnection conn)
{
String inputString = null;
try
{
DataInputStream dis = conn.openDataInputStream();
inputString = dis.readUTF();
dis.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return inputString;
}
/**
* 输出响应
*
* @param outputData
* @param conn
*/
private void sendOutputData(String outputData, StreamConnection conn)
{
try
{
DataOutputStream dos = conn.openDataOutputStream();
dos.writeUTF(outputData);
dos.close();
}
catch (IOException e)
{
}
}
/**
* 内部类,服务端服务线程。
*
* @author Jagie
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code style - Code Templates
*/
private class ClientProcessor implements Runnable
{
private Thread processorThread;
private Vector queue = new Vector();
// private boolean isOk = true;
ClientProcessor()
{
processorThread = new Thread(this);
processorThread.start();
}
public void run()
{
while (!isClosed)
{
synchronized (this)
{
if (queue.size() == 0)
{
try
{
// 阻塞,直到有新客户连接
wait();
}
catch (InterruptedException e)
{
}
}
}
// 处理连接队列
StreamConnection conn;
synchronized (this)
{
if (isClosed)
{
return;
}
conn = (StreamConnection) queue.firstElement();
queue.removeElementAt(0);
processConnection(conn);
}
}
}
/**
* 往连接队列添加新连接,同时唤醒处理线程
*
* @param conn
*/
void addConnection(StreamConnection conn)
{
synchronized (this)
{
queue.addElement(conn);
notify();
}
}
}
public void commandAction(Command c, Displayable d)
{
// TODO 自动生成方法存根
}
}
class Client implements Runnable, DiscoveryListener, CommandListener
{
public Session session;
public LocalDevice localDevice;
public StreamConnectionNotifier notifier;
public DiscoveryAgent discoveryAgent;
public ServiceRecord serviceRecord;
public StreamConnection conn;
// 设备集合
Vector devices = new Vector();
// 服务集合
Vector records = new Vector();
// 服务搜索的事务id集合
int[] transIDs;
boolean isClosed;
boolean isBTReady;
boolean isConnected;
private UUID[] uuidSet;
public String url;
private static UUID ECHO_SERVER_UUID= new UUID("A8D4EDAAC0394FEC9F90283162D1D8D2",false);
public Client(Session session)
{
// TODO 自动生成构造函数存根
super();
this.session = session;
System.out.println("client start");
isConnected = false;
new Thread(this).start();
}
public StreamConnection getConnections()
{
System.out.println("Client try to conn");
if ( isConnected )
{
System.out.println("has get a conn");
return conn;
}
System.out.println("try to get a url");
ServiceRecord sr = (ServiceRecord) records.elementAt(0);
url = sr.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
System.out.println("get the url");
try
{
conn = (StreamConnection) Connector.open(url);
System.out.println("get conn");
}
catch (IOException e)
{
// TODO 自动生成 catch 块
System.out.println("a err on Client");
e.printStackTrace();
isConnected =false;
}
isConnected = true;
while( !isConnected );
System.out.println("Client send");
return conn;
}
public synchronized void run()
{
// TODO 自动生成方法存根
System.out.println("Client running");
isBTReady = false;
try
{
LocalDevice localDevice = LocalDevice.getLocalDevice();
discoveryAgent = localDevice.getDiscoveryAgent();
isBTReady = true;
}
catch (Exception e)
{
e.printStackTrace();
}
if (!isBTReady)
{
showInfo("蓝牙不可用");
// 删除Gauge
return;
}
uuidSet = new UUID[2];
// 标志我们的响应服务的UUID集合
uuidSet[0] = new UUID(0x1101);
uuidSet[1] = ECHO_SERVER_UUID;
try
{
// IAC:Inquiry Access Code 查询访问码
// GIAC: 通用查询访问码
// 找到一个设备就append到数组devices中去
// 当发现一个设备的时候就调用public void deviceDiscovered(RemoteDevice btDevice,
// DeviceClass cod)
// 发现完毕就调用public void inquiryCompleted(int discType),用以唤醒wait的线程
discoveryAgent.startInquiry(DiscoveryAgent.GIAC, this);
}
catch (BluetoothStateException e)
{
}
try
{
// 阻塞,由inquiryCompleted()回调方法唤醒
wait();
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
showInfo("设备搜索完毕,共找到" + devices.size() + "个设备,开始搜索服务");
transIDs = new int[devices.size()];
for (int i = 0; i < devices.size(); i++)
{
RemoteDevice rd = (RemoteDevice) devices.elementAt(i);
try
{
// 记录每一次服务搜索的事务id
System.out.println("transIDs");
// 检查服务过程中会调用public void servicesDiscovered(int transID,
// ServiceRecord[] servRecord)
// 服务查找完毕,调用serviceSearchCompleted(),在所有设备都搜索完的情况下唤醒
transIDs[i] = discoveryAgent.searchServices(null, uuidSet, rd, this);
System.out.println("end transIDs");
}
catch (BluetoothStateException e)
{
continue;
}
}
try
{
// 阻塞,由serviceSearchCompleted()回调方法在所有设备都搜索完的情况下唤醒
wait();
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
showInfo("服务搜索完毕,共找到" + records.size() + "个服务,准备发送连接请求");
getConnections();
}
private void showInfo(String s)
{
System.out.println(s);
}
/**
* 回调方法
*/
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod)
{
if (devices.indexOf(btDevice) == -1)
{
devices.addElement(btDevice);
}
}
/**
* 回调方法,唤醒初始化线程
*/
public void inquiryCompleted(int discType)
{
synchronized (this)
{
notify();
}
}
/**
* 回调方法
*/
public void servicesDiscovered(int transID, ServiceRecord[] servRecord)
{
System.out.println("services Discovered");
for (int i = 0; i < servRecord.length; i++)
{
System.out.println("services Discovered eee:" + i);
records.addElement(servRecord[i]);
}
}
/**
* 回调方法,唤醒初始化线程
*/
public void serviceSearchCompleted(int transID, int respCode)
{
System.out.println("services Discovered end");
for (int i = 0; i < transIDs.length; i++)
{
if (transIDs[i] == transID)
{
transIDs[i] = -1;
break;
}
}
// 如果所有的设备都已经搜索服务完毕,则唤醒初始化线程。
boolean finished = true;
for (int i = 0; i < transIDs.length; i++)
{
if (transIDs[i] != -1)
{
finished = false;
break;
}
}
if (finished)
{
synchronized (this)
{
notify();
}
}
}
public void commandAction(Command c, Displayable d)
{
// TODO 自动生成方法存根
//getConnections();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -