【问题标题】:Java Video Chat applicataion input output stream not workingJava视频聊天应用程序输入输出流不起作用
【发布时间】:2019-03-23 08:01:56
【问题描述】:

我正在制作一个视频聊天应用程序,它使用 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();
            }
        }

【问题讨论】:

  • 您正在进入一个无限循环,在客户端没有中断条件。是什么让您从内部 while 循环中中断,以从外部循环内的网络摄像头读取新图像?
  • 我更正了错误,但仍然无法正常工作。我在服务器端添加了一个调试System.out.println() 来打印长度,这是输出4465 8917 13388 17869 22323 26786 31233 35694 40168 44637 49116 53596 58062 62546 67038 -657982985 Exception in thread "main" java.lang.NegativeArraySizeException at ServerSide.ServerWorker.run(ServerWorker.java:39) at ServerSide.Server.<init>(Server.java:42) at ServerSide.ServerMain.main(ServerMain.java:7)

标签: java networking video datainputstream dataoutputstream


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多