2014-02-12 129 views
2

我在一個基於套接字的java應用程序工作。它獲取客戶端的屏幕並在服務器上的GUI中顯示它。但問題是它只顯示客戶端的屏幕時間程序已啓動並且不更改它。這裏是我的代碼 服務器端:即時屏幕捕獲Java

try { 
    img = ImageIO.read(socket.getInputStream()); 

    while(true){ 
     ImageIcon icon = new ImageIcon(img); 
     label.setIcon(icon); 
    } 
} 
catch (IOException e) {} 

客戶端:

public class Client{ 

    public static void main(String[] args) throws Exception{ 

BufferedImage screenShot = new Robot().createScreenCapture(new   
Rectangle(Toolkit.getDefaultToolkit().getScreenSize())); 
ImageIO.write(screenShot, "PNG", socket.getOutputStream()); 
    public static void main(String[] args) throws Exception{ 
    Socket socket = new Socket("localhost",1999); 
    Chat chat = new Chat(socket);  
    Thread thread = new Thread(chat); 
    thread.start(); 
}  
} 


class Chat implements Runnable{ 
private Socket socket; 

public Chat(Socket socket){ 
    this.socket = socket; 

} 

@Override 
public void run() { 
    // TODO Auto-generated method stub 
    try{ while(true){ 
    BufferedImage screenShot = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize())); 
    ImageIO.write(screenShot, "PNG", socket.getOutputStream()); 
    }}catch(Exception e){} 


}} 

錯誤: - 螺紋
例外 「線程3」 java.lang.IndexOutOfBoundsException
at javax.imageio.stream.FileCacheImageOutputStream.seek(Unknown Source)
在javax.imageio.stream.FileCacheImageOutputStream.close(來源不明)
在com.sun.imageio.stream.StreamCloser $ CloseAction.performAction(來源不明)在com.sun.imageio.stream.StreamCloser $ 1.run
(來源不明)
在java.lang.Thread.run(來源不明)
UPDATE:
其實我關閉連接已建立,是造成錯誤甚至在插座。否則尼克的代碼就好了。

+0

你剛纔讀和一次寫的形象呢?循環做! (在服務器上移動imageio.read,在客戶端完成screencapture功能!)。也許在一個定時器5秒 –

+0

你的意思是我shud添加while(true)循環在客戶端文件? – Cybershadow

+0

是的,否則你只上傳一張截圖,因爲代碼只執行一次。在服務器上,你必須更頻繁地讀取套接字(創建一個5秒左右的計時器......)。 –

回答

1

因爲目前還不清楚,我想確保您已經產生了ImageIO.read調用正在運行的新線程;此行可能會阻塞該線程,直到發送某個內容以供其讀取。你做而不是希望在EDT上執行。

假設你有這個,我建議你使用SwingUtilities.invokeLater來更新GUI。這是標準的過程 - 它所做的是將更新放入隊列中,所以下一次GUI想要更新時,它知道該怎麼做。

這麼幹脆,你的代碼應該是這個樣子:

Thread awesomeThread = new Thread(new Runnable(){ 

    @Override 
    public void run() { 
     while(true){ 

      try{ 
       //Read the image 
       final Image img = ImageIO.read(socket.getInputStream()); 
       System.out.println("Image Read"); //code for troubleshooting 

       //Once an image is read, notify the GUI to update 
       SwingUtilities.invokeLater(new Runnable(){ 
        @Override 
        public void run() { 
         ImageIcon icon = new ImageIcon(img); 
         label.setIcon(icon); 
         System.out.println("Image updated"); //code for troubleshooting 
        }}); 
      } catch (IOException e) {} 
     } 
    }}); 

    awesomeThread.start(); 
+0

好吧,現在我得到一個新的Exception,客戶端文件中的ImageIo.write行中的java.lang.IndexOutOfBoundsException。可能是什麼原因造成的? – Cybershadow

+0

我看不到任何代碼在你的示例中與索引有關,所以我懷疑你需要發佈更多的代碼。但它很可能與數組或ArrayList有關。堆棧跟蹤是否在任何時候引用您的代碼?這應該會給你造成問題的線路。 –

+0

實際上堆棧沒有給出line.it只是說在線程3中的異常 – Cybershadow