Search code examples
javasocketstcpjavax.imageio

Java Sockets With Continuous Communication


I want to be able to do the following on the client side:

  • Open socket
  • Send Data
  • Wait
  • Send More Data

And server side:

  • Open msocket
  • Recive data
  • Wait
  • Keep recivieng (Loop over and over)

Currently i cant make it loop :(

I have client side:

Constctor:

s = new Socket(ServerIPAddr, 6100);
out = new ObjectOutputStream(s.getOutputStream());

Looping function:

    public void sendImage(BufferedImage image){

    System.out.println("Starting to send");
    try {

        ImageIO.write(image, "PNG", out);
        System.out.println("Sent");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } // png is lossless

}

This can be called many times one after another.

Server side i have consturctor:

    public ServerConnectionThread(Socket clientSocket) {current = clientSocket;}

Run function:

    public void run() {
    int i = 0;
    System.out.println("Connection accepted");
    System.out.println("Threaded spanwed");
    try {ObjectInputStream in = new ObjectInputStream(current.getInputStream());
        while (capturing) {
            ImageIO.write(ImageIO.read(in), "PNG", new File("test" + i++
                    + ".png"));
            in.close();
        }
    } catch (IOException e) {e.printStackTrace();}

}

Does anyone know why it only works for the first piece of data sent? And refuses to continuosuly sending?

-UPDATE-

while (capturing) {
            BufferedImage b = ImageIO.read(in);
            if(b == null){
                continue;
            }
            ImageIO.write(b, "PNG", new File("test" + i++
                    + ".png"));

        }

Seems to fix this issue


Solution

  • Why you are closing inputStream ?

    Try this -

     while (capturing) {
                ImageIO.write(ImageIO.read(in), "PNG", new File("test" + i++ ".png"));
                //in.close();
          }