01: /*
02: * Copyright 2001-2005 The Apache Software Foundation
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
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: public static final void readWrite(final InputStream remoteInput,
38: final OutputStream remoteOutput,
39: final InputStream localInput, final OutputStream localOutput) {
40: Thread reader, writer;
41:
42: reader = new Thread() {
43: public void run() {
44: int ch;
45:
46: try {
47: while (!interrupted()
48: && (ch = localInput.read()) != -1) {
49: remoteOutput.write(ch);
50: remoteOutput.flush();
51: }
52: } catch (IOException e) {
53: //e.printStackTrace();
54: }
55: }
56: };
57:
58: writer = new Thread() {
59: public void run() {
60: try {
61: Util.copyStream(remoteInput, localOutput);
62: } catch (IOException e) {
63: e.printStackTrace();
64: System.exit(1);
65: }
66: }
67: };
68:
69: writer.setPriority(Thread.currentThread().getPriority() + 1);
70:
71: writer.start();
72: reader.setDaemon(true);
73: reader.start();
74:
75: try {
76: writer.join();
77: reader.interrupt();
78: } catch (InterruptedException e) {
79: }
80: }
81:
82: }
|