-1

朋友们!我想在我的电脑中获取远程电脑屏幕!我试过用UDP写,现在我想用TCP协议写,但是有一些问题!如果有人能告诉我什么是我将不胜感激的问题......这是我的代码:Server.java

public Server(int port){
    this.G_PORT = port;
}
void sendMessage() throws IOException, AWTException{
    servSocket = new ServerSocket(G_PORT);
    System.out.println("Waiting...");
    cSocket = servSocket.accept();
    System.out.println("Server has connected to " + cSocket.getRemoteSocketAddress() + " on " + cSocket.getPort() +" port");

        BufferedOutputStream buffOS = new BufferedOutputStream(cSocket.getOutputStream());
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        Rectangle r = new Rectangle(d);

        KeyStroke keyStr = KeyStroke.getKeyStroke("ESCAPE");

        FileInputStream fileIN = null;
        OutputStream out = null;

    //while(keyStr.getKeyCode() != 27){
        bot = new Robot();
        buffIMG = bot.createScreenCapture(r);
        ImageIO.write(buffIMG, "jpeg", new File("D:\\ScreenShots\\test.jpeg"));
        fileIN = new FileInputStream(new File("D:\\ScreenShots\\test.jpeg"));
        out = cSocket.getOutputStream();
        int read, readTotal = 0;
        byteToIMG = new byte[BUFF_SIZE];

        while((read =  fileIN.read())!= -1){
            out.write(byteToIMG,0,read);
            System.out.println("IMG sended");
        }
    //}
    out.close();
    fileIN.close();
    cSocket.close();        
} 

和 Client.java

void recievMessage(long starTime) throws UnknownHostException, IOException{
    cSocket = new Socket(InetAddress.getByName(G_HOST), G_PORT);
    System.out.println("Connected");
    JFrame frame = new JFrame("My frame");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    JLabel label = new JLabel();
    ImageIcon icon;

    InputStream in = cSocket.getInputStream();
    byteToIMG = new byte[BYTE_SIZE];
    int read;
    int readTotal = 0;
        while((read = in.read(byteToIMG)) != -1){
            readTotal += read;
            InputStream imgIN = new ByteArrayInputStream(byteToIMG);
            buffIMG = ImageIO.read(imgIN);
            icon = new ImageIcon();
            icon.setImage(buffIMG);
            label.setIcon(icon);
            frame.getContentPane().add(label, BorderLayout.CENTER);
            frame.pack();
            System.out.println("IMG recieved");
        }
} 

请帮忙解决这个问题!如果您有其他解决方案建议!谢谢!

4

1 回答 1

2

您假设套接字上的每次读取都会提供一个完整的图像。你不能这样假设。它可能只提供一个字节。

幸运的是,它比这简单得多:

buffImg = Imageio.read(in);

在发件人处也简单得多。您不需要该文件。打电话

ImageIO.write(buffImg, "jpeg", out);
于 2013-02-15T01:14:37.960 回答