我有一个在线程上运行的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);
            }
        }
    }

最佳答案

好吧,您必须知道您的应用协议是什么才能理解它。听起来另一端正在使用序列化,您需要阅读它。有关ObjectOutputStream和ObjectInputStream的信息,请参见Javadoc。如果此假设正确,则您需要的是ObjectInputStream.readObject()。如果不是,则只需要找出它们向您发送的内容并相应地进行操作即可,可能使用DataInputStream来处理各种数据类型。

10-07 19:59