我有一个InputStream
,它在线程上运行并读取通过网络传递的任何数据。我的问题是 - 如何区分 InputStream
对象接收到的字节?例如如果接收到的字节指向 Car 对象,则执行某些操作,如果接收到的字节指向 Person 对象,则执行其他操作。
谢谢。
编辑:这是我的代码片段。看起来还好吗?抱歉,我是网络编程新手。
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final ObjectOutputStream mmObjOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "create ConnectedThread");
mmSocket = socket;
InputStream tmpIn = null;
ObjectOutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
mmInStream = tmpIn;
mmObjOutStream = tmpOut;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
Log.i(TAG, "PERFORMING MESSAGE READ");
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(GameboardResourceActivity.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
/**
* Write to the connected OutStream.
* @param buffer The bytes to write
*/
public void write(CardResource buffer) {
try {
mmObjOutStream.writeObject(buffer);
System.out.println("Reached here at least........");
// Share the sent message back to the UI Activity
mHandler.obtainMessage(GameboardResourceActivity.MESSAGE_WRITE, -1, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
最佳答案
你必须知道你的应用程序协议(protocol)是什么才能理解它。听起来另一端正在使用序列化,您需要阅读它。请参阅 ObjectOutputStream 和 ObjectInputStream 的 Javadoc。如果这个假设正确的话,你需要的是 ObjectInputStream.readObject() 。如果不是,您只需找出他们向您发送的内容并进行相应操作,可能使用 DataInputStream 来处理各种数据类型。
关于Java:区分InputStream中的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8252382/