Source Code : Pipes for Communications

Java Is Open Source Programming Language You Can Download From Java and Java Libraries From http://www.oracle.com. Click Here to download
We provide this code related to title for you to solve your developing problem easily. Libraries which is import in this program you can download from http://www.oracle.com. Click Here or search from google with Libraries Name you get jar file related it

Pipes for Communications

 

import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

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();
    }
  }
}
    

 

Thank with us