Java Video Chat应用程序输入输出流不起作用

问题描述 投票:1回答:1

我正在制作一个视频聊天应用程序,它使用java网络(也称为套接字)将网络摄像头的图像发送到另一个客户端。

我的代码首先发送缓冲图像数据的长度,然后发送实际数据。服务器还首先读取一个int然后读取数据本身。第一个图像工作但在它之后,数据输入流读取负数作为长度。

服务器端:

frame = new JFrame();
        while (true) {
            try {

                length = input.readInt();
                System.out.println(length);
                imgbytes = new byte[length];
                input.read(imgbytes);
                imginput = new ByteArrayInputStream(imgbytes);
                img = ImageIO.read(imginput);
                frame.getContentPane().add(new JLabel(new ImageIcon(img)));
                frame.pack();
                frame.setVisible(true);

            }
            catch(IOException e){
            e.printStackTrace();
            }
        }

客户端:

while(true) {
            try {

                    currentimg = webcam.getImage();
                    ImageIO.write(currentimg, "jpg", imgoutputstream);
                    imgbytes = imgoutputstream.toByteArray();
                    out.writeInt(imgbytes.length);
                    out.write(imgbytes);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
java networking video datainputstream dataoutputstream
1个回答
2
投票

在客户端,您始终将新映像写入现有流。这导致每次迭代中的数组大小增加。在java中,int最多有2147483647。如果你增加这个整数,它会跳到最小值auf int,这是负数(见this article)。

因此,要修复此错误,您需要在写入下一个图像之前清除流,以使大小永远不会大于整数最大值。

© www.soinside.com 2019 - 2024. All rights reserved.