1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package examples;
17
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.io.OutputStream;
21 import org.apache.commons.net.io.Util;
22
23 /***
24 * This is a utility class providing a reader/writer capability required
25 * by the weatherTelnet, rexec, rshell, and rlogin example programs.
26 * The only point of the class is to hold the static method readWrite
27 * which spawns a reader thread and a writer thread. The reader thread
28 * reads from a local input source (presumably stdin) and writes the
29 * data to a remote output destination. The writer thread reads from
30 * a remote input source and writes to a local output destination.
31 * The threads terminate when the remote input source closes.
32 * <p>
33 ***/
34
35 public final class IOUtil
36 {
37
38 public static final void readWrite(final InputStream remoteInput,
39 final OutputStream remoteOutput,
40 final InputStream localInput,
41 final OutputStream localOutput)
42 {
43 Thread reader, writer;
44
45 reader = new Thread()
46 {
47 public void run()
48 {
49 int ch;
50
51 try
52 {
53 while (!interrupted() && (ch = localInput.read()) != -1)
54 {
55 remoteOutput.write(ch);
56 remoteOutput.flush();
57 }
58 }
59 catch (IOException e)
60 {
61
62 }
63 }
64 }
65 ;
66
67
68 writer = new Thread()
69 {
70 public void run()
71 {
72 try
73 {
74 Util.copyStream(remoteInput, localOutput);
75 }
76 catch (IOException e)
77 {
78 e.printStackTrace();
79 System.exit(1);
80 }
81 }
82 };
83
84
85 writer.setPriority(Thread.currentThread().getPriority() + 1);
86
87 writer.start();
88 reader.setDaemon(true);
89 reader.start();
90
91 try
92 {
93 writer.join();
94 reader.interrupt();
95 }
96 catch (InterruptedException e)
97 {
98 }
99 }
100
101 }
102