Mình đang làm một remote desktop app theo giao thức TCP, gửi ảnh lần đầu thành công nhưng gặp lỗi Java.lang.nullPointerException ở những lần tiếp theo, code của mình như sau:
Đối với bên gửi, mình sẽ gửi image dưới dạng mảng byte, đầu tiên mình sẽ gửi kích thước mảng byte, sau đó mình sẽ gửi ảnh.
public void run() {
BufferedImage image = null;
try {
os = clientSocket.getOutputStream();
} catch (IOException e1) {
System.out.println(e1.getMessage());
}
while(continueLoop) {
//send captured screen
image = robot.createScreenCapture(rectangle);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
byte[] size = ByteBuffer.allocate(4).putInt(baos.size()).array();
os.write(size);
os.write(baos.toByteArray());
os.flush();
} catch(IOException e) {
e.printStackTrace();
e.printStackTrace();
continueLoop = false;
}
try {
Thread.sleep(30);
} catch(InterruptedException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
Đối với bên nhận:
public void run() {
Rectangle clientScreenDim = null; //lấy kích thước màn hình
boolean continueLoop = true;
clientScreenDim = new Rectangle();
try {
DataInputStream configGraphicStream = new DataInputStream(clientSocket.getInputStream());
//Vẽ giao diện, cái này đã chạy đúng
drawGUI();
InputStream is = clientSocket.getInputStream();
BufferedImage image = null;
while(continueLoop) {
// Lấy kích thước mảng byte
byte[] sizeInByte = new byte[64];
is.read(sizeInByte);
int length = ByteBuffer.wrap(sizeInByte).asIntBuffer().get();
try {
byte[] img = new byte[length];
// nhận ảnh
configGraphicStream.readFully(img);
image = ImageIO.read(new ByteArrayInputStream(img));
}
catch (Exception e) {
System.out.println(e.getMessage());
}
if( image != null)
{
// Vẽ ảnh lên panel
Graphics graphics = clientPanel.getGraphics();
graphics.drawImage(image, 0, 0, clientPanel.getWidth(), clientPanel.getHeight(), clientPanel);
}
System.out.println("Receiving image");
Thread.sleep(30); // mình muốn gửi 30 khung hình trong 1 giây
try {
clientScreenDim.setSize(image.getWidth(), image.getHeight());
new ClientCommandSender(clientSocket, clientPanel, clientScreenDim);
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
hiện tại lỗi nullPointerException đang trỏ vào dòng:
clientScreenDim.setSize(image.getWidth, image.getHeight);
Mình cũng chỉ mới code java nên chưa biết nhiều, mong mọi người góp ý giúp đỡ.