gpt4 book ai didi

通过套接字发送图像时的Java OutOfMemory

转载 作者:行者123 更新时间:2023-11-29 07:53:23 27 4
gpt4 key购买 nike

我创建了一个应用程序,基本上使用机器人在客户端获取图像并每隔几秒发送一次到服务器,这样我就可以看到另一台 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) {
}
}
}

最佳答案

在没有看到您的代码的情况下,我可以提供的唯一具体提示是使用内存分析器,例如 VisualVMYourKit .

某些地方正在保留对它可能不应该引用的对象的引用。

关于通过套接字发送图像时的Java OutOfMemory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19591874/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com