2014-02-07 33 views
0

我正在將圖像從服務器傳輸到客戶端。服務器捕獲屏幕並將其轉換爲字節數組和客戶端接收字節數組並將其轉換爲圖像。但傳輸僅在少數幀發生,然後發生錯誤。在java客戶端獲取負字節數組長度或大量字節數組長度

接收側:

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)                                    

請幫me..what從服務器圖像的連續傳輸做以更快的方式在java中通過套接字到客戶端。

回答

1

您正在使用

DataInputStream#read(byte[]) 

它(檢查它的Javadoc)並不能保證數據的完整陣列的價值將被讀取。此方法用於緩衝讀取並且不完全讀取請求的字節數量。

相反,你必須調用

DataInputStream#readFully(byte[]) 

其中有一個合同相適應你的目的(再次檢查的Javadoc)。

+0

是它的工作。謝謝。 – user3283519