2014-02-12 53 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