?? btconnection.java
字號:
import javax.microedition.io.*;
import java.io.*;
/**
* 該類描述了藍牙連接,提供了發送/接收數據的功能。
*/
public class BTConnection implements Runnable {
//
private GobangMIDlet midlet;
private StreamConnection sconn; //流連接
private DataOutputStream dos; //數據輸出流,用于發送數據
private DataInputStream dis; //數據輸入流,用于接收數據
private boolean connected; //是否連接
private Thread sendThread; //發送數據線程
private Thread receiveThread; //接收數據線程
private int[] sendData; //發送數據緩存區
//構造方法,創建藍牙連接對象
public BTConnection(GobangMIDlet midlet, StreamConnection sconn) throws IOException {
this.midlet = midlet;
this.sconn = sconn;
dos = sconn.openDataOutputStream();
dis = sconn.openDataInputStream();
sendData = new int[2];
connected = true;
//創建并啟動接收\發送數據線程
receiveThread = new Thread(this);
sendThread = new Thread(this);
receiveThread.start();
sendThread.start();
}
//發送數據
public void send(final int x, final int y) {
sendData[0] = x;
sendData[1] = y;
synchronized(this) {
notifyAll(); //通知發送線程發送緩沖區中的數據
}
}
//關閉連接
public void close() {
if(connected) {
try {
connected = false;
dos.close();
dos = null;
dis.close();
dis = null;
sconn.close();
sconn = null;
synchronized(this) {
notifyAll();
}
}
catch(IOException ioe) {
}
}
}
//接收/發送數據線程執行體
public void run() {
while(connected) {
try {
//發送數據線程
if(Thread.currentThread() == sendThread) {
synchronized(this) {
try {
wait(); //等待通知
}
catch(InterruptedException ie) {
System.out.println("ie = " + ie);
}
}
if(dos != null) {
dos.writeInt(sendData[0]);
dos.writeInt(sendData[1]);
}
}
//接收數據線程
else if(Thread.currentThread() == receiveThread) {
if(dis != null) {
//讀取數據,如果流中沒有數據,該方法將阻塞當前線程。
int x = dis.readInt();
int y = dis.readInt();
midlet.otherPlay(x, y); //對方下子
}
}
}
catch(IOException ioe) {
close();
midlet.release();
}
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -