001 /*
002 * Copyright 2000-2001 Sun Microsystems, Inc. All Rights Reserved.
003 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004 *
005 * This code is free software; you can redistribute it and/or modify it
006 * under the terms of the GNU General Public License version 2 only, as
007 * published by the Free Software Foundation. Sun designates this
008 * particular file as subject to the "Classpath" exception as provided
009 * by Sun in the LICENSE file that accompanied this code.
010 *
011 * This code is distributed in the hope that it will be useful, but WITHOUT
012 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
014 * version 2 for more details (a copy is included in the LICENSE file that
015 * accompanied this code).
016 *
017 * You should have received a copy of the GNU General Public License version
018 * 2 along with this work; if not, write to the Free Software Foundation,
019 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
020 *
021 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
022 * CA 95054 USA or visit www.sun.com if you need additional information or
023 * have any questions.
024 */
025
026 package java.nio.channels;
027
028 import java.io.IOException;
029 import java.net.Socket;
030 import java.net.SocketAddress;
031 import java.nio.ByteBuffer;
032 import java.nio.channels.spi.*;
033
034 /**
035 * A selectable channel for stream-oriented connecting sockets.
036 *
037 * <p> Socket channels are not a complete abstraction of connecting network
038 * sockets. Binding, shutdown, and the manipulation of socket options must be
039 * done through an associated {@link java.net.Socket} object obtained by
040 * invoking the {@link #socket() socket} method. It is not possible to create
041 * a channel for an arbitrary, pre-existing socket, nor is it possible to
042 * specify the {@link java.net.SocketImpl} object to be used by a socket
043 * associated with a socket channel.
044 *
045 * <p> A socket channel is created by invoking one of the {@link #open open}
046 * methods of this class. A newly-created socket channel is open but not yet
047 * connected. An attempt to invoke an I/O operation upon an unconnected
048 * channel will cause a {@link NotYetConnectedException} to be thrown. A
049 * socket channel can be connected by invoking its {@link #connect connect}
050 * method; once connected, a socket channel remains connected until it is
051 * closed. Whether or not a socket channel is connected may be determined by
052 * invoking its {@link #isConnected isConnected} method.
053 *
054 * <p> Socket channels support <i>non-blocking connection:</i> A socket
055 * channel may be created and the process of establishing the link to the
056 * remote socket may be initiated via the {@link #connect connect} method for
057 * later completion by the {@link #finishConnect finishConnect} method.
058 * Whether or not a connection operation is in progress may be determined by
059 * invoking the {@link #isConnectionPending isConnectionPending} method.
060 *
061 * <p> The input and output sides of a socket channel may independently be
062 * <i>shut down</i> without actually closing the channel. Shutting down the
063 * input side of a channel by invoking the {@link java.net.Socket#shutdownInput
064 * shutdownInput} method of an associated socket object will cause further
065 * reads on the channel to return <tt>-1</tt>, the end-of-stream indication.
066 * Shutting down the output side of the channel by invoking the {@link
067 * java.net.Socket#shutdownOutput shutdownOutput} method of an associated
068 * socket object will cause further writes on the channel to throw a {@link
069 * ClosedChannelException}.
070 *
071 * <p> Socket channels support <i>asynchronous shutdown,</i> which is similar
072 * to the asynchronous close operation specified in the {@link Channel} class.
073 * If the input side of a socket is shut down by one thread while another
074 * thread is blocked in a read operation on the socket's channel, then the read
075 * operation in the blocked thread will complete without reading any bytes and
076 * will return <tt>-1</tt>. If the output side of a socket is shut down by one
077 * thread while another thread is blocked in a write operation on the socket's
078 * channel, then the blocked thread will receive an {@link
079 * AsynchronousCloseException}.
080 *
081 * <p> Socket channels are safe for use by multiple concurrent threads. They
082 * support concurrent reading and writing, though at most one thread may be
083 * reading and at most one thread may be writing at any given time. The {@link
084 * #connect connect} and {@link #finishConnect finishConnect} methods are
085 * mutually synchronized against each other, and an attempt to initiate a read
086 * or write operation while an invocation of one of these methods is in
087 * progress will block until that invocation is complete. </p>
088 *
089 *
090 * @author Mark Reinhold
091 * @author JSR-51 Expert Group
092 * @version 1.41, 07/05/06
093 * @since 1.4
094 */
095
096 public abstract class SocketChannel extends AbstractSelectableChannel
097 implements ByteChannel, ScatteringByteChannel,
098 GatheringByteChannel {
099
100 /**
101 * Initializes a new instance of this class.
102 */
103 protected SocketChannel(SelectorProvider provider) {
104 super (provider);
105 }
106
107 /**
108 * Opens a socket channel.
109 *
110 * <p> The new channel is created by invoking the {@link
111 * java.nio.channels.spi.SelectorProvider#openSocketChannel
112 * openSocketChannel} method of the system-wide default {@link
113 * java.nio.channels.spi.SelectorProvider} object. </p>
114 *
115 * @return A new socket channel
116 *
117 * @throws IOException
118 * If an I/O error occurs
119 */
120 public static SocketChannel open() throws IOException {
121 return SelectorProvider.provider().openSocketChannel();
122 }
123
124 /**
125 * Opens a socket channel and connects it to a remote address.
126 *
127 * <p> This convenience method works as if by invoking the {@link #open()}
128 * method, invoking the {@link #connect(SocketAddress) connect} method upon
129 * the resulting socket channel, passing it <tt>remote</tt>, and then
130 * returning that channel. </p>
131 *
132 * @param remote
133 * The remote address to which the new channel is to be connected
134 *
135 * @throws AsynchronousCloseException
136 * If another thread closes this channel
137 * while the connect operation is in progress
138 *
139 * @throws ClosedByInterruptException
140 * If another thread interrupts the current thread
141 * while the connect operation is in progress, thereby
142 * closing the channel and setting the current thread's
143 * interrupt status
144 *
145 * @throws UnresolvedAddressException
146 * If the given remote address is not fully resolved
147 *
148 * @throws UnsupportedAddressTypeException
149 * If the type of the given remote address is not supported
150 *
151 * @throws SecurityException
152 * If a security manager has been installed
153 * and it does not permit access to the given remote endpoint
154 *
155 * @throws IOException
156 * If some other I/O error occurs
157 */
158 public static SocketChannel open(SocketAddress remote)
159 throws IOException {
160 SocketChannel sc = open();
161 try {
162 sc.connect(remote);
163 } finally {
164 if (!sc.isConnected()) {
165 try {
166 sc.close();
167 } catch (IOException x) {
168 }
169 }
170 }
171 assert sc.isConnected();
172 return sc;
173 }
174
175 /**
176 * Returns an operation set identifying this channel's supported
177 * operations.
178 *
179 * <p> Socket channels support connecting, reading, and writing, so this
180 * method returns <tt>(</tt>{@link SelectionKey#OP_CONNECT}
181 * <tt>|</tt> {@link SelectionKey#OP_READ} <tt>|</tt> {@link
182 * SelectionKey#OP_WRITE}<tt>)</tt>. </p>
183 *
184 * @return The valid-operation set
185 */
186 public final int validOps() {
187 return (SelectionKey.OP_READ | SelectionKey.OP_WRITE | SelectionKey.OP_CONNECT);
188 }
189
190 // -- Socket-specific operations --
191
192 /**
193 * Retrieves a socket associated with this channel.
194 *
195 * <p> The returned object will not declare any public methods that are not
196 * declared in the {@link java.net.Socket} class. </p>
197 *
198 * @return A socket associated with this channel
199 */
200 public abstract Socket socket();
201
202 /**
203 * Tells whether or not this channel's network socket is connected. </p>
204 *
205 * @return <tt>true</tt> if, and only if, this channel's network socket
206 * is connected
207 */
208 public abstract boolean isConnected();
209
210 /**
211 * Tells whether or not a connection operation is in progress on this
212 * channel. </p>
213 *
214 * @return <tt>true</tt> if, and only if, a connection operation has been
215 * initiated on this channel but not yet completed by invoking the
216 * {@link #finishConnect finishConnect} method
217 */
218 public abstract boolean isConnectionPending();
219
220 /**
221 * Connects this channel's socket.
222 *
223 * <p> If this channel is in non-blocking mode then an invocation of this
224 * method initiates a non-blocking connection operation. If the connection
225 * is established immediately, as can happen with a local connection, then
226 * this method returns <tt>true</tt>. Otherwise this method returns
227 * <tt>false</tt> and the connection operation must later be completed by
228 * invoking the {@link #finishConnect finishConnect} method.
229 *
230 * <p> If this channel is in blocking mode then an invocation of this
231 * method will block until the connection is established or an I/O error
232 * occurs.
233 *
234 * <p> This method performs exactly the same security checks as the {@link
235 * java.net.Socket} class. That is, if a security manager has been
236 * installed then this method verifies that its {@link
237 * java.lang.SecurityManager#checkConnect checkConnect} method permits
238 * connecting to the address and port number of the given remote endpoint.
239 *
240 * <p> This method may be invoked at any time. If a read or write
241 * operation upon this channel is invoked while an invocation of this
242 * method is in progress then that operation will first block until this
243 * invocation is complete. If a connection attempt is initiated but fails,
244 * that is, if an invocation of this method throws a checked exception,
245 * then the channel will be closed. </p>
246 *
247 * @param remote
248 * The remote address to which this channel is to be connected
249 *
250 * @return <tt>true</tt> if a connection was established,
251 * <tt>false</tt> if this channel is in non-blocking mode
252 * and the connection operation is in progress
253 *
254 * @throws AlreadyConnectedException
255 * If this channel is already connected
256 *
257 * @throws ConnectionPendingException
258 * If a non-blocking connection operation is already in progress
259 * on this channel
260 *
261 * @throws ClosedChannelException
262 * If this channel is closed
263 *
264 * @throws AsynchronousCloseException
265 * If another thread closes this channel
266 * while the connect operation is in progress
267 *
268 * @throws ClosedByInterruptException
269 * If another thread interrupts the current thread
270 * while the connect operation is in progress, thereby
271 * closing the channel and setting the current thread's
272 * interrupt status
273 *
274 * @throws UnresolvedAddressException
275 * If the given remote address is not fully resolved
276 *
277 * @throws UnsupportedAddressTypeException
278 * If the type of the given remote address is not supported
279 *
280 * @throws SecurityException
281 * If a security manager has been installed
282 * and it does not permit access to the given remote endpoint
283 *
284 * @throws IOException
285 * If some other I/O error occurs
286 */
287 public abstract boolean connect(SocketAddress remote)
288 throws IOException;
289
290 /**
291 * Finishes the process of connecting a socket channel.
292 *
293 * <p> A non-blocking connection operation is initiated by placing a socket
294 * channel in non-blocking mode and then invoking its {@link #connect
295 * connect} method. Once the connection is established, or the attempt has
296 * failed, the socket channel will become connectable and this method may
297 * be invoked to complete the connection sequence. If the connection
298 * operation failed then invoking this method will cause an appropriate
299 * {@link java.io.IOException} to be thrown.
300 *
301 * <p> If this channel is already connected then this method will not block
302 * and will immediately return <tt>true</tt>. If this channel is in
303 * non-blocking mode then this method will return <tt>false</tt> if the
304 * connection process is not yet complete. If this channel is in blocking
305 * mode then this method will block until the connection either completes
306 * or fails, and will always either return <tt>true</tt> or throw a checked
307 * exception describing the failure.
308 *
309 * <p> This method may be invoked at any time. If a read or write
310 * operation upon this channel is invoked while an invocation of this
311 * method is in progress then that operation will first block until this
312 * invocation is complete. If a connection attempt fails, that is, if an
313 * invocation of this method throws a checked exception, then the channel
314 * will be closed. </p>
315 *
316 * @return <tt>true</tt> if, and only if, this channel's socket is now
317 * connected
318 *
319 * @throws NoConnectionPendingException
320 * If this channel is not connected and a connection operation
321 * has not been initiated
322 *
323 * @throws ClosedChannelException
324 * If this channel is closed
325 *
326 * @throws AsynchronousCloseException
327 * If another thread closes this channel
328 * while the connect operation is in progress
329 *
330 * @throws ClosedByInterruptException
331 * If another thread interrupts the current thread
332 * while the connect operation is in progress, thereby
333 * closing the channel and setting the current thread's
334 * interrupt status
335 *
336 * @throws IOException
337 * If some other I/O error occurs
338 */
339 public abstract boolean finishConnect() throws IOException;
340
341 // -- ByteChannel operations --
342
343 /**
344 * @throws NotYetConnectedException
345 * If this channel is not yet connected
346 */
347 public abstract int read(ByteBuffer dst) throws IOException;
348
349 /**
350 * @throws NotYetConnectedException
351 * If this channel is not yet connected
352 */
353 public abstract long read(ByteBuffer[] dsts, int offset, int length)
354 throws IOException;
355
356 /**
357 * @throws NotYetConnectedException
358 * If this channel is not yet connected
359 */
360 public final long read(ByteBuffer[] dsts) throws IOException {
361 return read(dsts, 0, dsts.length);
362 }
363
364 /**
365 * @throws NotYetConnectedException
366 * If this channel is not yet connected
367 */
368 public abstract int write(ByteBuffer src) throws IOException;
369
370 /**
371 * @throws NotYetConnectedException
372 * If this channel is not yet connected
373 */
374 public abstract long write(ByteBuffer[] srcs, int offset, int length)
375 throws IOException;
376
377 /**
378 * @throws NotYetConnectedException
379 * If this channel is not yet connected
380 */
381 public final long write(ByteBuffer[] srcs) throws IOException {
382 return write(srcs, 0, srcs.length);
383 }
384
385 }
|