[英]Instantaneous Screen Capture Java
我正在基於套接字的Java應用程序上工作。它獲取客戶端的屏幕並將其顯示在服務器上的GUI中,但問題是它只是在程序啟動時顯示客戶端的屏幕而沒有更改。 這是我的代碼服務器端:
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){}
}}
錯誤:-
線程“ Thread-3”中的異常java.lang.IndexOutOfBoundsException
在javax.imageio.stream.FileCacheImageOutputStream.seek中(未知源)
在javax.imageio.stream.FileCacheImageOutputStream.close(未知來源)
在com.sun.imageio.stream.StreamCloser $ CloseAction.performAction(未知來源)
在com.sun.imageio.stream.StreamCloser $ 1.run(未知源)
在java.lang.Thread.run(未知來源)
更新:
實際上我什至在建立連接之前就已經關閉了套接字,這導致了錯誤。 其他尼克的代碼工作正常。
因為不清楚,所以我想確保您產生了一個正在運行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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.