我的程序拍摄用户屏幕的图片,当他们使用我的程序时,制作屏幕截图,然后将其发送到服务器。图像将加载大约1/4的路径并冻结。
发送屏幕截图:
BufferedImage buffimg = robot.createScreenCapture(captureSize);
BufferedImage image = buffimg;
byte[] imageInByte;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
baos.flush();
imageInByte = baos.toByteArray();
baos.close();
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.println("!SCREENDATA!");
out.flush();
dos.writeInt(baos.toByteArray().length);
dos.write(baos.toByteArray());
dos.flush();
获取图片:
if (input.startsWith("!SCREENDATA!")) {
System.out.println("reading");
DataInputStream dis = new DataInputStream(socket.getInputStream());
int len = dis.readInt();
System.out.println(len);
byte[] data = new byte[len];
dis.read(data);
InputStream in = new ByteArrayInputStream(data);
Image image = Toolkit.getDefaultToolkit().createImage(data);
v.repaint(image);
}
显示图像:
public void repaint(Image img) {
frame.getContentPane().add(new JLabel(new ImageIcon(img)));
frame.repaint();
frame.pack();
}
如果有人能帮助我,我会非常感激!
答案 0 :(得分:1)
你需要继续调用dis.read(data);
,因为TCP套接字上的这个方法并不是为了在一次调用中提供整个缓冲区(它是一个流套接字,它会继续)。但请注意,当套接字没有数据要提供时,方法调用将被阻止。此外,最好在文件之前发送文件大小,以便另一端知道预期多少 - 它不太容易出现可能导致无限循环的协议错误。
查看how to achieve transfer file between client and server using java socket的答案。
无论如何,一个类比:插座有一个装满512kb的水桶,比方说。你有一个2048kb的桶。你必须不断地将插座桶倒入自己的水桶中。
另外,除非在事件发送线程上,否则不要使用Swing。有关详细信息,请参阅How do you use the Event Dispatch Thread?。