首页 > 解决方案 > 使用java进行屏幕共享

问题描述

我使用 java 找到了这个屏幕共享代码。这是它接收屏幕的客户端。

客户端 :

    class ReceiveScreen extends Thread{
    private ObjectInputStream cObjectInputStream = null;
    private JPanel cPanel = null;
    private boolean continueLoop = true;
    InputStream oin = null;
    Image image1 = null;

    public ReceiveScreen(InputStream in,JPanel p){
        oin = in;
        cPanel = p;
        start();
    }

    public void run(){
        try{
            //Read screenshots of the client and then draw them
            while(continueLoop){
                byte[] bytes = new byte[1024*1024];
                int count = 0;
                do{
                    count+=oin.read(bytes,count,bytes.length-count);
                }while(!(count>4 && bytes[count-2]==(byte)-1 && bytes[count-1]==(byte)-39));

                image1 = ImageIO.read(new ByteArrayInputStream(bytes));
                image1 = image1.getScaledInstance(cPanel.getWidth(),cPanel.getHeight(),Image.SCALE_FAST);

                //Draw the received screenshots

                Graphics graphics = cPanel.getGraphics();
                graphics.drawImage(image1, 0, 0, cPanel.getWidth(), cPanel.getHeight(), cPanel);
            }

        } catch(IOException ex) {
            ex.printStackTrace();
        }
    }
}

谁能解释一下这个while条件有什么作用?

while(!(count>4 && bytes[count-2]==(byte)-1 && bytes[count-1]==(byte)-39));

查看服务器端

标签: javaswingscreensharing

解决方案


  1. 它从套接字读取字节,直到至少有 4 个字节。

  2. 然后它检查最后两个字节的幻数,表示图像的结束。

  3. 然后它从原始字节创建图像对象。

  4. 然后它将图像对象绘制到屏幕上。

(并且它一直重复此操作,直到continuteloop设置为 false。

你应该学习 DeMorgan 的 therom。它允许重写条件

while(!(count>4 && bytes[count-2]==(byte)-1 && bytes[count-1]==(byte)-39));

是相同的

while ( count < 4 || bytes[count-2] != (byte)-1 || bytes[count-1] != (byte)-39 );

这使条件更加清晰。

  • 必须读取四个字节
  • 倒数第二个字节必须是 0xFF
  • 最后一个字节必须是 0xD9

如果您查看 JPEG 图像规范格式,您会看到 0xFFD9 是一个“JPEG 标记”,它表示“图像流的结束”

因此,此循环有效地从套接字读取 JPEG 图像并显示它,直到continuteloop标志设置为 false。


推荐阅读