?? 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 + -