1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.commons.net.telnet;
17
18 import java.io.IOException;
19 import java.io.OutputStream;
20
21 /***
22 *
23 * <p>
24 *
25 * <p>
26 * <p>
27 * @author Daniel F. Savarese
28 ***/
29
30
31 final class TelnetOutputStream extends OutputStream
32 {
33 private TelnetClient __client;
34 private boolean __convertCRtoCRLF = true;
35 private boolean __lastWasCR = false;
36
37 TelnetOutputStream(TelnetClient client)
38 {
39 __client = client;
40 }
41
42
43 /***
44 * Writes a byte to the stream.
45 * <p>
46 * @param ch The byte to write.
47 * @exception IOException If an error occurs while writing to the underlying
48 * stream.
49 ***/
50 public void write(int ch) throws IOException
51 {
52
53 synchronized (__client)
54 {
55 ch &= 0xff;
56
57 if (__client._requestedWont(TelnetOption.BINARY))
58 {
59 if (__lastWasCR)
60 {
61 if (__convertCRtoCRLF)
62 {
63 __client._sendByte('\n');
64 if (ch == '\n')
65 {
66 __lastWasCR = false;
67 return ;
68 }
69 }
70 else if (ch != '\n')
71 __client._sendByte('\0');
72 }
73
74 __lastWasCR = false;
75
76 switch (ch)
77 {
78 case '\r':
79 __client._sendByte('\r');
80 __lastWasCR = true;
81 break;
82 case TelnetCommand.IAC:
83 __client._sendByte(TelnetCommand.IAC);
84 __client._sendByte(TelnetCommand.IAC);
85 break;
86 default:
87 __client._sendByte(ch);
88 break;
89 }
90 }
91 else if (ch == TelnetCommand.IAC)
92 {
93 __client._sendByte(ch);
94 __client._sendByte(TelnetCommand.IAC);
95 }
96 else
97 __client._sendByte(ch);
98 }
99 }
100
101
102 /***
103 * Writes a byte array to the stream.
104 * <p>
105 * @param buffer The byte array to write.
106 * @exception IOException If an error occurs while writing to the underlying
107 * stream.
108 ***/
109 public void write(byte buffer[]) throws IOException
110 {
111 write(buffer, 0, buffer.length);
112 }
113
114
115 /***
116 * Writes a number of bytes from a byte array to the stream starting from
117 * a given offset.
118 * <p>
119 * @param buffer The byte array to write.
120 * @param offset The offset into the array at which to start copying data.
121 * @param length The number of bytes to write.
122 * @exception IOException If an error occurs while writing to the underlying
123 * stream.
124 ***/
125 public void write(byte buffer[], int offset, int length) throws IOException
126 {
127 synchronized (__client)
128 {
129 while (length-- > 0)
130 write(buffer[offset++]);
131 }
132 }
133
134 /*** Flushes the stream. ***/
135 public void flush() throws IOException
136 {
137 __client._flushOutputStream();
138 }
139
140 /*** Closes the stream. ***/
141 public void close() throws IOException
142 {
143 __client._closeOutputStream();
144 }
145 }