我在使用BT实现PC和android之间的通信时遇到了一个问题。我有一个使用标准 java Socket 及其流在 WIFI 通信上正常工作的应用程序。我正在尝试添加 Bt 通信。安卓端打开流的代码使用标准的BluetoothSocket(通信建立,没问题):
mOos = new ObjectOutputStream(btSocket.getOutputStream());
mOos.flush();
mOis = new ObjectInputStream(btSocket.getInputStream());
在 PC 端,我使用 Bluecove 2.1。
mOos = new ObjectOutputStream(mStreamConn.openOutputStream());
mOos .flush();
mOis = new ObjectInputStream(mStreamConn.openInputStream());
流已正确初始化。我正在从 android 向 PC 发送初始消息
protected synchronized void sendAwaitingMsg() throws IOException {
Message msg;
while((msg = mOutgoingMsgQueue.poll()) != null) {
mOos.writeObject(msg);
}
mOos.flush();
}
然后尝试在PC端阅读
protected void getIncomingMsg() throws IOException, ClassNotFoundException {
if(mOis.available() > 0) {
Message msg = (Message)mOis.readObject();
if(msg.mControlHeader > 0) {
mKeepRunning = false;
} else {
msg.setHandlerId(mId);
mConnectionManager.acceptNewMessage(msg);
}
}
}
但是 mOis.available() 始终为 0,这意味着它不接收发送消息。我的消息对象类:
public class Message extends LinkedHashMap implements Serializable, Comparable {
static final long serialVersionUID = 10275539472837495L;
protected long mHandlerId;
protected int mType;
protected int mPriority;
public int mControlHeader = 0;
public int getType() {
return mType;
}
public void setType(int type) {
this.mType = type;
}
public long getHandlerId() {
return mHandlerId;
}
public void setHandlerId(long handlerId) {
this.mHandlerId = handlerId;
}
public int getPriority() {
return mPriority;
}
public void setPriority(int priority) {
mPriority = priority;
}
@Override
public int compareTo(Object o) {
return mPriority - ((Message)o).mPriority;
}
}
同样的操作,在标准的 java 套接字上,网络通信就像一个魅力。哪里有问题?