Java I/O How to - Use Pipe Stream for Communications








Question

We would like to know how to use Pipe Stream for Communications.

Answer

import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
/*  w  w  w  . j  av a2  s  .  c o m*/
public class Pipe {
  public static void main(String args[]) throws Exception {
    PipedInputStream in = new PipedInputStream();
    PipedOutputStream out = new PipedOutputStream(in);

    Sender s = new Sender(out);
    Receiver r = new Receiver(in);
    Thread t1 = new Thread(s);
    Thread t2 = new Thread(r);
    t1.start();
    t2.start();
  }
}

class Sender implements Runnable {
  OutputStream out;

  public Sender(OutputStream out) {
    this.out = out;
  }

  public void run() {
    byte value;

    try {
      for (int i = 0; i < 5; i++) {
        value = (byte) (Math.random() * 256);
        System.out.print("About to send " + value + ".. ");
        out.write(value);
        System.out.println("..sent..");
        Thread.sleep((long) (Math.random() * 1000));
      }
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

class Receiver implements Runnable {
  InputStream in;

  public Receiver(InputStream in) {
    this.in = in;
  }

  public void run() {
    int value;

    try {
      while ((value = in.read()) != -1) {
        System.out.println("received " + (byte) value);
      }
      System.out.println("Pipe closed");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

The code above generates the following result.