在java中,在客户端获得负字节数组长度或大量字节数组长度

时间:2014-02-07 11:37:26

标签: java sockets

我正在将图像从服务器传输到客户端。服务器捕获屏幕并将其转换为字节数组和客户端接收字节数组并将其转换回图像。但传输只发生在几帧,然后发生错误。

接收方:

while(true) {
    DataInputStream dis = new DataInputStream(csocket.getInputStream());
    int len = dis.readInt();
    System.out.println(len);
    byte data[] = null;
    data = new byte[len];
    dis.read(data);
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    BufferedImage image1=ImageIO.read(in);
    ImageIcon imageIcon= new ImageIcon(image1);
    Image image = imageIcon.getImage();
    image = image.getScaledInstance(cPanel.getWidth(),cPanel.getHeight(),Image.SCALE_FAST);
    //Draw the recieved screenshot
    Graphics graphics = cPanel.getGraphics();
    graphics.drawImage(image, 0, 0, cPanel.getWidth(),cPanel.getHeight(),cPanel);
}

发件人方:

while(continueLoop) {
    try {
        BufferedImage image = robot.createScreenCapture(rectangle);
        byte[] imageInByte;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image,"jpg", baos);
        baos.flush();
        imageInByte = baos.toByteArray();
        baos.close();
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        //PrintWriter out = new PrintWriter(socket.getOutputStream());

        //out.flush();
        dos.writeInt(imageInByte.length);
        System.out.println(imageInByte.length);
        dos.write(imageInByte);
        Thread.sleep(1000);
        dos.flush();
    }
    catch(Exception e) {
    }
}

接收者的输出:

 1177222283
 -297418067
 1228900861
 -412483840
 189486847
 10536391
 -33405441
 12898815
 740182
 -16736067
 -805436987 
 -16726825
 258150991
 2137853087
 1917408603
 512024791 
 -1227886373
 -1034512766
 1772271848
 157387
 Exception in thread "Thread-3" java.lang.NullPointerException
 at javax.swing.ImageIcon.<init>(ImageIcon.java:228)
 at remoteclient.ClientScreenReciever.run(ClientScreenReciever.java:65)                                                                                                                                            

请帮助我......如何在java中以更快的方式在服务器上通过套接字连续传输图像。

1 个答案:

答案 0 :(得分:1)

您正在使用

DataInputStream#read(byte[])

(检查其Javadoc)不保证将读取完整的数组值数据。此方法用于缓冲读取,而不是完全读取请求的字节数。

相反,你必须打电话

DataInputStream#readFully(byte[])

有合同适合你的目的(再次检查Javadoc)。