1/*
2 * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package java.nio.channels;
27
28import java.io.IOException;
29import java.net.Socket;
30import java.net.SocketOption;
31import java.net.SocketAddress;
32import java.nio.ByteBuffer;
33import java.nio.channels.spi.AbstractSelectableChannel;
34import java.nio.channels.spi.SelectorProvider;
35
36/**
37 * A selectable channel for stream-oriented connecting sockets.
38 *
39 * <p> A socket channel is created by invoking one of the {@link #open open}
40 * methods of this class.  It is not possible to create a channel for an arbitrary,
41 * pre-existing socket. A newly-created socket channel is open but not yet
42 * connected.  An attempt to invoke an I/O operation upon an unconnected
43 * channel will cause a {@link NotYetConnectedException} to be thrown.  A
44 * socket channel can be connected by invoking its {@link #connect connect}
45 * method; once connected, a socket channel remains connected until it is
46 * closed.  Whether or not a socket channel is connected may be determined by
47 * invoking its {@link #isConnected isConnected} method.
48 *
49 * <p> Socket channels support <i>non-blocking connection:</i>&nbsp;A socket
50 * channel may be created and the process of establishing the link to the
51 * remote socket may be initiated via the {@link #connect connect} method for
52 * later completion by the {@link #finishConnect finishConnect} method.
53 * Whether or not a connection operation is in progress may be determined by
54 * invoking the {@link #isConnectionPending isConnectionPending} method.
55 *
56 * <p> Socket channels support <i>asynchronous shutdown,</i> which is similar
57 * to the asynchronous close operation specified in the {@link Channel} class.
58 * If the input side of a socket is shut down by one thread while another
59 * thread is blocked in a read operation on the socket's channel, then the read
60 * operation in the blocked thread will complete without reading any bytes and
61 * will return <tt>-1</tt>.  If the output side of a socket is shut down by one
62 * thread while another thread is blocked in a write operation on the socket's
63 * channel, then the blocked thread will receive an {@link
64 * AsynchronousCloseException}.
65 *
66 * <p> Socket options are configured using the {@link #setOption(SocketOption,Object)
67 * setOption} method. Socket channels support the following options:
68 * <blockquote>
69 * <table border summary="Socket options">
70 *   <tr>
71 *     <th>Option Name</th>
72 *     <th>Description</th>
73 *   </tr>
74 *   <tr>
75 *     <td> {@link java.net.StandardSocketOptions#SO_SNDBUF SO_SNDBUF} </td>
76 *     <td> The size of the socket send buffer </td>
77 *   </tr>
78 *   <tr>
79 *     <td> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </td>
80 *     <td> The size of the socket receive buffer </td>
81 *   </tr>
82 *   <tr>
83 *     <td> {@link java.net.StandardSocketOptions#SO_KEEPALIVE SO_KEEPALIVE} </td>
84 *     <td> Keep connection alive </td>
85 *   </tr>
86 *   <tr>
87 *     <td> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </td>
88 *     <td> Re-use address </td>
89 *   </tr>
90 *   <tr>
91 *     <td> {@link java.net.StandardSocketOptions#SO_LINGER SO_LINGER} </td>
92 *     <td> Linger on close if data is present (when configured in blocking mode
93 *          only) </td>
94 *   </tr>
95 *   <tr>
96 *     <td> {@link java.net.StandardSocketOptions#TCP_NODELAY TCP_NODELAY} </td>
97 *     <td> Disable the Nagle algorithm </td>
98 *   </tr>
99 * </table>
100 * </blockquote>
101 * Additional (implementation specific) options may also be supported.
102 *
103 * <p> Socket channels are safe for use by multiple concurrent threads.  They
104 * support concurrent reading and writing, though at most one thread may be
105 * reading and at most one thread may be writing at any given time.  The {@link
106 * #connect connect} and {@link #finishConnect finishConnect} methods are
107 * mutually synchronized against each other, and an attempt to initiate a read
108 * or write operation while an invocation of one of these methods is in
109 * progress will block until that invocation is complete.  </p>
110 *
111 * @author Mark Reinhold
112 * @author JSR-51 Expert Group
113 * @since 1.4
114 */
115
116public abstract class SocketChannel
117    extends AbstractSelectableChannel
118    implements ByteChannel, ScatteringByteChannel, GatheringByteChannel, NetworkChannel
119{
120
121    /**
122     * Initializes a new instance of this class.
123     *
124     * @param  provider
125     *         The provider that created this channel
126     */
127    protected SocketChannel(SelectorProvider provider) {
128        super(provider);
129    }
130
131    /**
132     * Opens a socket channel.
133     *
134     * <p> The new channel is created by invoking the {@link
135     * java.nio.channels.spi.SelectorProvider#openSocketChannel
136     * openSocketChannel} method of the system-wide default {@link
137     * java.nio.channels.spi.SelectorProvider} object.  </p>
138     *
139     * @return  A new socket channel
140     *
141     * @throws  IOException
142     *          If an I/O error occurs
143     */
144    public static SocketChannel open() throws IOException {
145        return SelectorProvider.provider().openSocketChannel();
146    }
147
148    /**
149     * Opens a socket channel and connects it to a remote address.
150     *
151     * <p> This convenience method works as if by invoking the {@link #open()}
152     * method, invoking the {@link #connect(SocketAddress) connect} method upon
153     * the resulting socket channel, passing it <tt>remote</tt>, and then
154     * returning that channel.  </p>
155     *
156     * @param  remote
157     *         The remote address to which the new channel is to be connected
158     *
159     * @return  A new, and connected, socket channel
160     *
161     * @throws  AsynchronousCloseException
162     *          If another thread closes this channel
163     *          while the connect operation is in progress
164     *
165     * @throws  ClosedByInterruptException
166     *          If another thread interrupts the current thread
167     *          while the connect operation is in progress, thereby
168     *          closing the channel and setting the current thread's
169     *          interrupt status
170     *
171     * @throws  UnresolvedAddressException
172     *          If the given remote address is not fully resolved
173     *
174     * @throws  UnsupportedAddressTypeException
175     *          If the type of the given remote address is not supported
176     *
177     * @throws  SecurityException
178     *          If a security manager has been installed
179     *          and it does not permit access to the given remote endpoint
180     *
181     * @throws  IOException
182     *          If some other I/O error occurs
183     */
184    public static SocketChannel open(SocketAddress remote)
185        throws IOException
186    {
187        SocketChannel sc = open();
188        try {
189            sc.connect(remote);
190        } catch (Throwable x) {
191            try {
192                sc.close();
193            } catch (Throwable suppressed) {
194                x.addSuppressed(suppressed);
195            }
196            throw x;
197        }
198        assert sc.isConnected();
199        return sc;
200    }
201
202    /**
203     * Returns an operation set identifying this channel's supported
204     * operations.
205     *
206     * <p> Socket channels support connecting, reading, and writing, so this
207     * method returns <tt>(</tt>{@link SelectionKey#OP_CONNECT}
208     * <tt>|</tt>&nbsp;{@link SelectionKey#OP_READ} <tt>|</tt>&nbsp;{@link
209     * SelectionKey#OP_WRITE}<tt>)</tt>.  </p>
210     *
211     * @return  The valid-operation set
212     */
213    public final int validOps() {
214        return (SelectionKey.OP_READ
215                | SelectionKey.OP_WRITE
216                | SelectionKey.OP_CONNECT);
217    }
218
219
220    // -- Socket-specific operations --
221
222    /**
223     * @throws  ConnectionPendingException
224     *          If a non-blocking connect operation is already in progress on
225     *          this channel
226     * @throws  AlreadyBoundException               {@inheritDoc}
227     * @throws  UnsupportedAddressTypeException     {@inheritDoc}
228     * @throws  ClosedChannelException              {@inheritDoc}
229     * @throws  IOException                         {@inheritDoc}
230     * @throws  SecurityException
231     *          If a security manager has been installed and its
232     *          {@link SecurityManager#checkListen checkListen} method denies
233     *          the operation
234     *
235     * @since 1.7
236     */
237    @Override
238    public abstract SocketChannel bind(SocketAddress local)
239        throws IOException;
240
241    /**
242     * @throws  UnsupportedOperationException           {@inheritDoc}
243     * @throws  IllegalArgumentException                {@inheritDoc}
244     * @throws  ClosedChannelException                  {@inheritDoc}
245     * @throws  IOException                             {@inheritDoc}
246     *
247     * @since 1.7
248     */
249    @Override
250    public abstract <T> SocketChannel setOption(SocketOption<T> name, T value)
251        throws IOException;
252
253    /**
254     * Shutdown the connection for reading without closing the channel.
255     *
256     * <p> Once shutdown for reading then further reads on the channel will
257     * return {@code -1}, the end-of-stream indication. If the input side of the
258     * connection is already shutdown then invoking this method has no effect.
259     *
260     * @return  The channel
261     *
262     * @throws  NotYetConnectedException
263     *          If this channel is not yet connected
264     * @throws  ClosedChannelException
265     *          If this channel is closed
266     * @throws  IOException
267     *          If some other I/O error occurs
268     *
269     * @since 1.7
270     */
271    public abstract SocketChannel shutdownInput() throws IOException;
272
273    /**
274     * Shutdown the connection for writing without closing the channel.
275     *
276     * <p> Once shutdown for writing then further attempts to write to the
277     * channel will throw {@link ClosedChannelException}. If the output side of
278     * the connection is already shutdown then invoking this method has no
279     * effect.
280     *
281     * @return  The channel
282     *
283     * @throws  NotYetConnectedException
284     *          If this channel is not yet connected
285     * @throws  ClosedChannelException
286     *          If this channel is closed
287     * @throws  IOException
288     *          If some other I/O error occurs
289     *
290     * @since 1.7
291     */
292    public abstract SocketChannel shutdownOutput() throws IOException;
293
294    /**
295     * Retrieves a socket associated with this channel.
296     *
297     * <p> The returned object will not declare any public methods that are not
298     * declared in the {@link java.net.Socket} class.  </p>
299     *
300     * @return  A socket associated with this channel
301     */
302    public abstract Socket socket();
303
304    /**
305     * Tells whether or not this channel's network socket is connected.
306     *
307     * @return  <tt>true</tt> if, and only if, this channel's network socket
308     *          is {@link #isOpen open} and connected
309     */
310    public abstract boolean isConnected();
311
312    /**
313     * Tells whether or not a connection operation is in progress on this
314     * channel.
315     *
316     * @return  <tt>true</tt> if, and only if, a connection operation has been
317     *          initiated on this channel but not yet completed by invoking the
318     *          {@link #finishConnect finishConnect} method
319     */
320    public abstract boolean isConnectionPending();
321
322    /**
323     * Connects this channel's socket.
324     *
325     * <p> If this channel is in non-blocking mode then an invocation of this
326     * method initiates a non-blocking connection operation.  If the connection
327     * is established immediately, as can happen with a local connection, then
328     * this method returns <tt>true</tt>.  Otherwise this method returns
329     * <tt>false</tt> and the connection operation must later be completed by
330     * invoking the {@link #finishConnect finishConnect} method.
331     *
332     * <p> If this channel is in blocking mode then an invocation of this
333     * method will block until the connection is established or an I/O error
334     * occurs.
335     *
336     * <p> This method performs exactly the same security checks as the {@link
337     * java.net.Socket} class.  That is, if a security manager has been
338     * installed then this method verifies that its {@link
339     * java.lang.SecurityManager#checkConnect checkConnect} method permits
340     * connecting to the address and port number of the given remote endpoint.
341     *
342     * <p> This method may be invoked at any time.  If a read or write
343     * operation upon this channel is invoked while an invocation of this
344     * method is in progress then that operation will first block until this
345     * invocation is complete.  If a connection attempt is initiated but fails,
346     * that is, if an invocation of this method throws a checked exception,
347     * then the channel will be closed.  </p>
348     *
349     * @param  remote
350     *         The remote address to which this channel is to be connected
351     *
352     * @return  <tt>true</tt> if a connection was established,
353     *          <tt>false</tt> if this channel is in non-blocking mode
354     *          and the connection operation is in progress
355     *
356     * @throws  AlreadyConnectedException
357     *          If this channel is already connected
358     *
359     * @throws  ConnectionPendingException
360     *          If a non-blocking connection operation is already in progress
361     *          on this channel
362     *
363     * @throws  ClosedChannelException
364     *          If this channel is closed
365     *
366     * @throws  AsynchronousCloseException
367     *          If another thread closes this channel
368     *          while the connect operation is in progress
369     *
370     * @throws  ClosedByInterruptException
371     *          If another thread interrupts the current thread
372     *          while the connect operation is in progress, thereby
373     *          closing the channel and setting the current thread's
374     *          interrupt status
375     *
376     * @throws  UnresolvedAddressException
377     *          If the given remote address is not fully resolved
378     *
379     * @throws  UnsupportedAddressTypeException
380     *          If the type of the given remote address is not supported
381     *
382     * @throws  SecurityException
383     *          If a security manager has been installed
384     *          and it does not permit access to the given remote endpoint
385     *
386     * @throws  IOException
387     *          If some other I/O error occurs
388     */
389    public abstract boolean connect(SocketAddress remote) throws IOException;
390
391    /**
392     * Finishes the process of connecting a socket channel.
393     *
394     * <p> A non-blocking connection operation is initiated by placing a socket
395     * channel in non-blocking mode and then invoking its {@link #connect
396     * connect} method.  Once the connection is established, or the attempt has
397     * failed, the socket channel will become connectable and this method may
398     * be invoked to complete the connection sequence.  If the connection
399     * operation failed then invoking this method will cause an appropriate
400     * {@link java.io.IOException} to be thrown.
401     *
402     * <p> If this channel is already connected then this method will not block
403     * and will immediately return <tt>true</tt>.  If this channel is in
404     * non-blocking mode then this method will return <tt>false</tt> if the
405     * connection process is not yet complete.  If this channel is in blocking
406     * mode then this method will block until the connection either completes
407     * or fails, and will always either return <tt>true</tt> or throw a checked
408     * exception describing the failure.
409     *
410     * <p> This method may be invoked at any time.  If a read or write
411     * operation upon this channel is invoked while an invocation of this
412     * method is in progress then that operation will first block until this
413     * invocation is complete.  If a connection attempt fails, that is, if an
414     * invocation of this method throws a checked exception, then the channel
415     * will be closed.  </p>
416     *
417     * @return  <tt>true</tt> if, and only if, this channel's socket is now
418     *          connected
419     *
420     * @throws  NoConnectionPendingException
421     *          If this channel is not connected and a connection operation
422     *          has not been initiated
423     *
424     * @throws  ClosedChannelException
425     *          If this channel is closed
426     *
427     * @throws  AsynchronousCloseException
428     *          If another thread closes this channel
429     *          while the connect operation is in progress
430     *
431     * @throws  ClosedByInterruptException
432     *          If another thread interrupts the current thread
433     *          while the connect operation is in progress, thereby
434     *          closing the channel and setting the current thread's
435     *          interrupt status
436     *
437     * @throws  IOException
438     *          If some other I/O error occurs
439     */
440    public abstract boolean finishConnect() throws IOException;
441
442    /**
443     * Returns the remote address to which this channel's socket is connected.
444     *
445     * <p> Where the channel is bound and connected to an Internet Protocol
446     * socket address then the return value from this method is of type {@link
447     * java.net.InetSocketAddress}.
448     *
449     * @return  The remote address; {@code null} if the channel's socket is not
450     *          connected
451     *
452     * @throws  ClosedChannelException
453     *          If the channel is closed
454     * @throws  IOException
455     *          If an I/O error occurs
456     *
457     * @since 1.7
458     */
459    public abstract SocketAddress getRemoteAddress() throws IOException;
460
461    // -- ByteChannel operations --
462
463    /**
464     * @throws  NotYetConnectedException
465     *          If this channel is not yet connected
466     */
467    public abstract int read(ByteBuffer dst) throws IOException;
468
469    /**
470     * @throws  NotYetConnectedException
471     *          If this channel is not yet connected
472     */
473    public abstract long read(ByteBuffer[] dsts, int offset, int length)
474        throws IOException;
475
476    /**
477     * @throws  NotYetConnectedException
478     *          If this channel is not yet connected
479     */
480    public final long read(ByteBuffer[] dsts) throws IOException {
481        return read(dsts, 0, dsts.length);
482    }
483
484    /**
485     * @throws  NotYetConnectedException
486     *          If this channel is not yet connected
487     */
488    public abstract int write(ByteBuffer src) throws IOException;
489
490    /**
491     * @throws  NotYetConnectedException
492     *          If this channel is not yet connected
493     */
494    public abstract long write(ByteBuffer[] srcs, int offset, int length)
495        throws IOException;
496
497    /**
498     * @throws  NotYetConnectedException
499     *          If this channel is not yet connected
500     */
501    public final long write(ByteBuffer[] srcs) throws IOException {
502        return write(srcs, 0, srcs.length);
503    }
504
505    /**
506     * {@inheritDoc}
507     * <p>
508     * If there is a security manager set, its {@code checkConnect} method is
509     * called with the local address and {@code -1} as its arguments to see
510     * if the operation is allowed. If the operation is not allowed,
511     * a {@code SocketAddress} representing the
512     * {@link java.net.InetAddress#getLoopbackAddress loopback} address and the
513     * local port of the channel's socket is returned.
514     *
515     * @return  The {@code SocketAddress} that the socket is bound to, or the
516     *          {@code SocketAddress} representing the loopback address if
517     *          denied by the security manager, or {@code null} if the
518     *          channel's socket is not bound
519     *
520     * @throws  ClosedChannelException     {@inheritDoc}
521     * @throws  IOException                {@inheritDoc}
522     */
523    @Override
524    public abstract SocketAddress getLocalAddress() throws IOException;
525
526}
527