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