两个线程侦听一个输入流

时间:2018-02-27 14:38:25

标签: java android multithreading sockets

我有一个镜像服务器屏幕的客户端服务器android应用程序, 服务器使用dataoutputstream超时发送屏幕截图,客户端接收它并将其设置为图像视图的源。我想要实现的是,当我点击一个按钮时,我会将一个字符串写入客户端并执行任务,但我遇到了问题。我创建了两个读取相同输入流的线程。

如何在接受服务器发送的图像时收听到达的字符串。

用于收听到达图像的线程1运行方法

@Override
    public void run() {
        //update UI for the stream
        Log.d("ShareService", "client side started");
        try {
            while (isConnected) {
                final byte[] bytes;
                int len = mDataInputStream.readInt();
                bytes = new byte[len];
                if (len > 0) {
                    mDataInputStream.readFully(bytes, 0, bytes.length);
                }
                clientActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ImageView iv = clientActivity.findViewById(R.id.image_view_screen_share);
                        Bitmap bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                        iv.setImageBitmap(bm);
                    }
                });
                bitmapReceive++;
                Log.d("Share Service", "Bitmap received: " + bitmapReceive);
            }
            Log.d("Share Service", "Client Disconnects");
            disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

用于侦听到达命令的线程2运行方法

    @Override
        public void run() {
            Log.d("ShareService", "screen pinning listener started");
            while (isConnected) {
                try {
                    String command = mDataInputStream.readUTF();
                    Log.d("ShareService", "Command has been received: " + command);
                    switch (command) {
                        case SCREEN_PIN_ON:
                            //start screen pinning
                            Log.d("ShareService", "ScreenPinning is on");
                            clientActivity.startLockTask();
                            break;
                        case SCREEN_PIN_OFF:
                            //stop screen pinning
                            Log.d("ShareService", "ScreenPinning is off");
                            clientActivity.stopLockTask();
                            break;
                        default:
                            break;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

我在第2个帖子上收到此错误消息

W/System.err: java.io.UTFDataFormatException: malformed input around byte 0
W/System.err:     at java.io.DataInputStream.readUTF(DataInputStream.java:656)
W/System.err:     at java.io.DataInputStream.readUTF(DataInputStream.java:564)
W/System.err:     at com.example.android.presentor.screenshare.ShareService$Client$1.run(ShareService.java:267)

0 个答案:

没有答案