我创建了一个应用程序,它基本上使用机器人在客户端获取和映像,并每隔几秒发送到服务器,这样我就可以观察另一台 PC 上发生的事情。问题似乎是它一直将图像保存在数组或其他东西中,因为几秒钟后,它就崩溃了。我只是收到图像并在收到时将其写在屏幕上。然而,过了一会儿,它给了我一个 OutOfMemory。有没有人暗示可能导致它的原因?
以下是请求的代码片段:
服务器:
private class Conexao extends Thread {
public static final int PORTA = 12000;
public ObjectOutputStream out;
public ObjectInputStream in;
public Image image;
private boolean fim;
public Conexao(String ip) throws IOException {
try {
Socket socket = new Socket(ip, Conexao.PORTA);
this.out = new ObjectOutputStream(socket.getOutputStream());
this.in = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
throw e;
}
}
public void encerrar() {
this.fim = true;
}
@Override
public void run() {
this.fim = false;
while (!this.fim) {
Mensagem mensagem = null;
try {
mensagem = ((Mensagem) in.readObject());
} catch (IOException | ClassNotFoundException e) {
}
if (mensagem != null) {
this.image = mensagem.getImage();
Cliente.this.painel.repaint();
}
}
}
}
客户:
private static class Conexao extends Thread {
private static Image CURSOR;
static {
try {
CURSOR = ImageIO.read(new File("images\\mouse.png"));
} catch (IOException e) {
CURSOR = null;
}
}
private ObjectOutputStream out;
private ObjectInputStream in;
public Conexao() throws IOException {
try {
ServerSocket serverSocket = new ServerSocket(Servidor.PORTA, 1);
Socket socket = serverSocket.accept();
this.out = new ObjectOutputStream(socket.getOutputStream());
this.in = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
throw e;
}
}
@Override
public void run() {
try {
Robot robot = new Robot();
for (;;)
try {
Thread.sleep(10);
Point p = MouseInfo.getPointerInfo().getLocation();
BufferedImage img = robot.createScreenCapture(new Rectangle(0, 0, Toolkit.getDefaultToolkit().getScreenSize().width, Toolkit.getDefaultToolkit().getScreenSize().height));
if (Conexao.CURSOR != null) {
img.getGraphics().drawImage(CURSOR, p.x, p.y, null);
} else {
Graphics2D g = (Graphics2D) img.getGraphics();
g.setColor(Color.WHITE);
g.fillOval(p.x - 5, p.y - 5, 10, 10);
g.setStroke(new BasicStroke(2));
g.setColor(Color.BLACK);
g.drawOval(p.x - 5, p.y - 5, 10, 10);
g.dispose();
}
this.out.writeObject(new Mensagem(img, p));
this.out.flush();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
} catch (AWTException e) {
}
}
}