📄 btserver.java
字号:
package com.j2medev.chapter9;
import java.io.*;
import java.util.Vector;
import javax.bluetooth.*;
import javax.microedition.io.*;
public class BTServer implements Runnable {
//存储BTMIDlet实例,方便回调
private BTMIDlet midlet = null;
private LocalDevice device = null;
private StreamConnectionNotifier server = null;
private ConnectionHandle handle = null;
private boolean stop = false;
public BTServer(BTMIDlet _midlet) {
this.midlet = _midlet;
}
public void run() {
try {
device = LocalDevice.getLocalDevice();
device.setDiscoverable(DiscoveryAgent.GIAC);
UUID u = new UUID(0x0001);
//启动SPP服务器
server = (StreamConnectionNotifier)Connector.open("btspp://localhost:"+u.toString());
midlet.btServerReady();
handle = new ConnectionHandle();
while(!stop){
StreamConnection conn = null;
try {
//将ServiceRecord注册到SDDB
conn = server.acceptAndOpen();
} catch (IOException ex) {
ex.printStackTrace();
continue;
}
//处理客户端的连接
handle.addConnection(conn);
}
} catch (BluetoothStateException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
//根据连接的类型,进行不同方式的处理
private void processConnection(Connection _conn){
if(_conn instanceof StreamConnection){
StreamConnection conn = (StreamConnection)_conn;
try {
//流连接
InputStream is = conn.openInputStream();
byte[] buffer = new byte[1024];
int ch = -1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while((ch = is.read(buffer))!= -1){
baos.write(buffer,0,ch);
}
byte[] img = baos.toByteArray();
midlet.imageReceived(img);
is.close();
baos.close();
conn.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}else if(_conn instanceof L2CAPConnection){
L2CAPConnection conn = (L2CAPConnection)_conn;
try {
//要充分考虑最大接受单元,避免丢失数据
int max = conn.getReceiveMTU();
byte[] buffer = new byte[max];
int len = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while(conn.ready()&&(len = conn.receive(buffer)) != -1){
baos.write(buffer,0,len);
}
byte[] img = baos.toByteArray();
midlet.imageReceived(img);
baos.close();
conn.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private class ConnectionHandle implements Runnable{
private Thread t = null;
//存储客户端连接
private Vector conns = new Vector();
ConnectionHandle(){
t = new Thread(this);
t.start();
}
public void run(){
while(!stop){
//如果conns为空,则线程进入等待状态
synchronized (this){
try {
if(conns.size() == 0)
wait();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
StreamConnection conn = null;
synchronized (this){
//取出第一个连接并删除掉
conn = (StreamConnection)conns.elementAt(0);
conns.removeElementAt(0);
//开始处理
processConnection(conn);
}
}
}
void addConnection(StreamConnection _conn){
//新连接到来,唤醒线程处理
synchronized(this){
conns.addElement(_conn);
notify();
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -