user439781
user439781

Reputation: 131

Images from server to client by socket

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:

  1. A thread taking snapshots of my screen and putting them in a queue
  2. Several threads reading from the queue and sending the images over a socket to a server

Server:

  1. A socket server that allows multiple connections and receives the image and put them in a queue
  2. 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.

Upvotes: 0

Views: 1948

Answers (2)

Óscar López
Óscar López

Reputation: 236150

Send (and receive) each image as a byte[], and preferably use a file format that compresses images, like .jpg. Don't forget to flush() the stream between images. And make sure to read all the bytes of an image before trying to read the next one.

Upvotes: 1

Jordan
Jordan

Reputation: 1

Sending images over a network is extremely hard. The reason being the files are so big it is literally almost impossible to send them without compressing them first. Try this link it might be able to help you since i cannot help much with out your code. How to send Image data type via socket in java Hope its helpful!

Upvotes: 0

Related Questions