Giả lập dịch vụ phản hồi thông tin bằng Pipe
Phần kế tiếp ta xây dựng một ứng dụng có tên là PipeEcho mô phỏng dịch vụ phản hồi thông tin để minh họa cách sử dụng Pipe làm phương tiện giao tiếp giữa các Thread trong một ứng dụng. Mô hình ứng dụng PipeEcho ...
Phần kế tiếp ta xây dựng một ứng dụng có tên là PipeEcho mô phỏng dịch vụ phản hồi thông tin để minh họa cách sử dụng Pipe làm phương tiện giao tiếp giữa các Thread trong một ứng dụng.

Trong ứng dụng này Client và Server là hai Thread thuộc lớp PipedEchoClient và PipedEchoServer. Việc trao đổi thông tin giữa client và server được thực hiện thông qua 2 Pipe (cwPipe-srPipe) và (swPipe-crPipe).
PipedEchoClient nhận các ký tự từ bàn phím, gởi chúng sang PipedEchoServer và chờ nhận các ký tự gởi về từ PipedEchoServer để in ra màn hình. PipedEchoServer chờ nhận từng ký tự từ PipedEchoClient, đổi ký tự nhận được thành ký tự hoa và gởi ngược về PipedEchoClient.
Lớp PipedEchoServer
Hãy lưu chương trình sau vào tập tin PipedEchoServer.java
import java.io.*; public class PipedEchoServer extends Thread { PipedInputStream readPipe; PipedOutputStream writePipe; PipedEchoServer(PipedInputStream readPipe, PipedOutputStream writePipe){ this.readPipe = readPipe; this.writePipe = writePipe; System.out.println("Server is starting . . ."); start(); } public void run(){ while(true) { try{ int ch = readPipe.read(); ch = Character.toUpperCase((char)ch); writePipe.write(ch); } catch (IOException ie) { System.out.println("Echo Server Error: "+ie ); } } } }
Lớp PipedEchoClient
Hãy lưu chương trình sau vào tập tin PipedEchoClient.java
import java.io.*; public class PipedEchoClient extends Thread { PipedInputStream readPipe; PipedOutputStream writePipe; PipedEchoClient(PipedInputStream readPipe, PipedOutputStream writePipe){ this.readPipe = readPipe; this.writePipe = writePipe; System.out.println("Client creation"); start(); } public void run(){ while(true) { try { int ch=System.in.read(); writePipe.write(ch); ch = readPipe.read(); System.out.print((char)ch); } catch(IOException ie){ System.out.println("Echo Client Error: "+ie ); } } } }
Lớp PipedEcho
Hãy lưu chương trình sau vào tập tin PipedEcho.java
import java.io.*; public class PipedEcho { public static void main(String argv[]){ try{ PipedOutputStream cwPipe = new PipedOutputStream(); PipedInputStream crPipe = new PipedInputStream(); PipedOutputStream swPipe = new PipedOutputStream(crPipe); PipedInputStream srPipe = new PipedInputStream(cwPipe); PipedEchoServer server = new PipedEchoServer(srPipe,swPipe); PipedEchoClient client = new PipedEchoClient(crPipe,cwPipe); } catch(IOException ie) { System.out.println("Pipe Echo Error:"+ie); } } }
Biên dịch và thực thi chương trình
Biên dịch và thực thi chương trình theo cách sau:

Nhập vào bàn phím chuỗi ký tự mà bạn muốn rồi nhấp phím Enter. Bạn sẽ thấy chuỗi ký tự in hoa của chuỗi vừa nhập xuất hiện trên màn hình.