I am writing a client-server program and I want that to send an image. The code is the following:
//RECEIVER
while(true){
try{
socket = server.accept();
out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
in = new ObjectInputStream(socket.getInputStream());
System.out.println("Connected to "+PORTA+".");
while(!socket.isClosed()){
System.out.println("\nPrint the action");
azione = reader.readLine();
if(azione.equals("screenshot")){
out.writeObject("screenshot");
out.flush();
BufferedImage screenshot = ImageIO.read(in);
ImageIO.write(screenshot, "jpg", new File("screenshot.jpg"));
}
}catch(Exception ex){
System.out.println("Not connected.\n");
}
}
And the server:
while(true){
try{
socket = new Socket(INDIRIZZO, PORT);
out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
in = new ObjectInputStream(socket.getInputStream());
while(!socket.isClosed()){
try {
action = (String)in.readObject();
if(azione.equals("screenshot")){
BufferedImage screenshot = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
ImageIO.write(screenshot, "jpg", out);
}catch(Exception e){
}
}
}catch(Exception ex){
//
}
}
My problem is that the client receive the image only if I close the socket or the out stream, but I don't want that to happen. How can I bypass that? How can I send the image as bytes? Thanks!
while(!socket.isClosed())
is not a valid test. It won't be true until you close it. You should test the result ofreadLine()
for null. But you shouldn't be mixing readers and writers and streams and buffered and unbuffered on the same socket anyway: it will never work. – Jacklight