Ive tried several solutions Ive found on the internet on how to send multipleimages over a socket, but I cant get it to work as I want. I have the following setup:
Client:
- A thread taking snapshots of my screen and putting them in a queue
- Several threads reading from the queue and sending the images over a socket to a server
Server:
- A socket server that allows multiple connections and receives the image and put them in a queue
- A thread that reads the queue and writes the images to a JPanel
My problem is that Im having a hard time to send the images over the socket, eg. keeping an open socket and just stream the images. I’ve tried different solutions, but only the first images are sent. If someone could share some code on how to write multiple images from one thread to another I would be very grateful.
Edit
It feels like each image is not flushed? I now create 1 thread to send with an open connection:
while(true)
{
BufferedImage imageQItem = (BufferedImage) queue.dequeue();
ImageIO.write(imageQItem,"jpg",out);//out is a dataoutputstream
}
And I then read it in (my socket server creates a new thread for the connection of the above client)
while(true)
{
System.out.println("Reading");
BufferedImage image = ImageIO.read(in);
viewer.setBufferedImage(image);
viewer.repaint();
}
All that happens is that it keeps printing reading. I don’t seem to get an end to each image.
Send (and receive) each image as a
byte[], and preferably use a file format that compresses images, like .jpg. Don’t forget toflush()the stream between images. And make sure to read all the bytes of an image before trying to read the next one.