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
26 package java.nio.channels;
27
28 import java.io.IOException;
29 import java.net.ProtocolFamily;
30 import java.net.Socket;
31 import java.net.SocketOption;
32 import java.net.SocketAddress;
33 import java.nio.ByteBuffer;
34 import java.nio.channels.spi.AbstractSelectableChannel;
35 import java.nio.channels.spi.SelectorProvider;
36 import static java.util.Objects.requireNonNull;
37
38 /**
39 * A selectable channel for stream-oriented connecting sockets.
40 *
41 * <p> A socket channel is created by invoking one of the {@link #open open}
42 * methods of this class. It is not possible to create a channel for an arbitrary,
43 * pre-existing socket. A newly-created socket channel is open but not yet
44 * connected. An attempt to invoke an I/O operation upon an unconnected
45 * channel will cause a {@link NotYetConnectedException} to be thrown. A
46 * socket channel can be connected by invoking its {@link #connect connect}
47 * method; once connected, a socket channel remains connected until it is
48 * closed. Whether or not a socket channel is connected may be determined by
49 * invoking its {@link #isConnected isConnected} method.
50 *
51 * <p> Socket channels support <i>non-blocking connection:</i> A socket
52 * channel may be created and the process of establishing the link to the
53 * remote socket may be initiated via the {@link #connect connect} method for
54 * later completion by the {@link #finishConnect finishConnect} method.
55 * Whether or not a connection operation is in progress may be determined by
56 * invoking the {@link #isConnectionPending isConnectionPending} method.
57 *
58 * <p> Socket channels support <i>asynchronous shutdown,</i> which is similar
59 * to the asynchronous close operation specified in the {@link Channel} class.
60 * If the input side of a socket is shut down by one thread while another
61 * thread is blocked in a read operation on the socket's channel, then the read
62 * operation in the blocked thread will complete without reading any bytes and
63 * will return {@code -1}. If the output side of a socket is shut down by one
64 * thread while another thread is blocked in a write operation on the socket's
65 * channel, then the blocked thread will receive an {@link
66 * AsynchronousCloseException}.
67 *
68 * <p> Socket options are configured using the {@link #setOption(SocketOption,Object)
69 * setOption} method. Socket channels support the following options:
70 * <blockquote>
71 * <table class="striped">
72 * <caption style="display:none">Socket options</caption>
73 * <thead>
74 * <tr>
75 * <th scope="col">Option Name</th>
76 * <th scope="col">Description</th>
77 * </tr>
78 * </thead>
79 * <tbody>
80 * <tr>
81 * <th scope="row"> {@link java.net.StandardSocketOptions#SO_SNDBUF SO_SNDBUF} </th>
82 * <td> The size of the socket send buffer </td>
83 * </tr>
84 * <tr>
85 * <th scope="row"> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </th>
86 * <td> The size of the socket receive buffer </td>
87 * </tr>
88 * <tr>
89 * <th scope="row"> {@link java.net.StandardSocketOptions#SO_KEEPALIVE SO_KEEPALIVE} </th>
90 * <td> Keep connection alive </td>
91 * </tr>
92 * <tr>
93 * <th scope="row"> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </th>
94 * <td> Re-use address </td>
95 * </tr>
96 * <tr>
97 * <th scope="row"> {@link java.net.StandardSocketOptions#SO_LINGER SO_LINGER} </th>
98 * <td> Linger on close if data is present (when configured in blocking mode
99 * only) </td>
100 * </tr>
101 * <tr>
102 * <th scope="row"> {@link java.net.StandardSocketOptions#TCP_NODELAY TCP_NODELAY} </th>
103 * <td> Disable the Nagle algorithm </td>
104 * </tr>
105 * </tbody>
106 * </table>
107 * </blockquote>
108 * Additional (implementation specific) options may also be supported.
109 *
110 * <p> Socket channels are safe for use by multiple concurrent threads. They
111 * support concurrent reading and writing, though at most one thread may be
112 * reading and at most one thread may be writing at any given time. The {@link
113 * #connect connect} and {@link #finishConnect finishConnect} methods are
114 * mutually synchronized against each other, and an attempt to initiate a read
115 * or write operation while an invocation of one of these methods is in
116 * progress will block until that invocation is complete. </p>
117 *
118 * @author Mark Reinhold
119 * @author JSR-51 Expert Group
120 * @since 1.4
121 */
122
123 public abstract class SocketChannel
124 extends AbstractSelectableChannel
125 implements ByteChannel, ScatteringByteChannel, GatheringByteChannel, NetworkChannel
126 {
127
128 /**
129 * Initializes a new instance of this class.
130 *
131 * @param provider
132 * The provider that created this channel
133 */
134 protected SocketChannel(SelectorProvider provider) {
135 super(provider);
136 }
137
138 /**
139 * Opens a socket channel.
140 *
141 * <p> The new channel is created by invoking the {@link
142 * java.nio.channels.spi.SelectorProvider#openSocketChannel
143 * openSocketChannel} method of the system-wide default {@link
144 * java.nio.channels.spi.SelectorProvider} object. </p>
145 *
146 * @return A new socket channel
147 *
148 * @throws IOException
149 * If an I/O error occurs
150 */
151 public static SocketChannel open() throws IOException {
152 return SelectorProvider.provider().openSocketChannel();
153 }
154
155 /**
156 * Opens a socket channel. The {@code family} parameter specifies the
157 * {@link ProtocolFamily protocol family} of the channel's socket.
158 *
159 * <p> The new channel is created by invoking the {@link
160 * java.nio.channels.spi.SelectorProvider#openSocketChannel(ProtocolFamily)
161 * openSocketChannel(ProtocolFamily)} method of the system-wide default.
162 * {@link java.nio.channels.spi.SelectorProvider} object.</p>
163 *
164 * @param family
165 * The protocol family
166 *
167 * @return A new socket channel
168 *
169 * @throws UnsupportedOperationException
170 * If the specified protocol family is not supported. For example,
171 * suppose the parameter is specified as {@link
172 * java.net.StandardProtocolFamily#INET6 StandardProtocolFamily.INET6}
173 * but IPv6 is not enabled on the platform.
174 * @throws IOException
175 * If an I/O error occurs
176 *
177 * @since 15
178 */
179 public static SocketChannel open(ProtocolFamily family) throws IOException {
180 return SelectorProvider.provider().openSocketChannel(requireNonNull(family));
181 }
182
183 /**
184 * Opens a socket channel and connects it to a remote address.
185 *
186 * <p> This convenience method works as if by invoking the {@link #open()}
187 * method, invoking the {@link #connect(SocketAddress) connect} method upon
188 * the resulting socket channel, passing it {@code remote}, and then
189 * returning that channel. </p>
190 *
191 * @param remote
192 * The remote address to which the new channel is to be connected
193 *
194 * @return A new, and connected, socket channel
195 *
196 * @throws AsynchronousCloseException
197 * If another thread closes this channel
198 * while the connect operation is in progress
199 *
200 * @throws ClosedByInterruptException
201 * If another thread interrupts the current thread
202 * while the connect operation is in progress, thereby
203 * closing the channel and setting the current thread's
204 * interrupt status
205 *
206 * @throws UnresolvedAddressException
207 * If the given remote address is not fully resolved
208 *
209 * @throws UnsupportedAddressTypeException
210 * If the type of the given remote address is not supported
211 *
212 * @throws SecurityException
213 * If a security manager has been installed
214 * and it does not permit access to the given remote endpoint
215 *
216 * @throws IOException
217 * If some other I/O error occurs
218 */
219 public static SocketChannel open(SocketAddress remote)
220 throws IOException
221 {
222 SocketChannel sc = open();
223 try {
224 sc.connect(remote);
225 } catch (Throwable x) {
226 try {
227 sc.close();
228 } catch (Throwable suppressed) {
229 x.addSuppressed(suppressed);
230 }
231 throw x;
232 }
233 assert sc.isConnected();
234 return sc;
235 }
236
237 /**
238 * Returns an operation set identifying this channel's supported
239 * operations.
240 *
241 * <p> Socket channels support connecting, reading, and writing, so this
242 * method returns {@code (}{@link SelectionKey#OP_CONNECT}
243 * {@code |} {@link SelectionKey#OP_READ} {@code |} {@link
244 * SelectionKey#OP_WRITE}{@code )}.
245 *
246 * @return The valid-operation set
247 */
248 public final int validOps() {
249 return (SelectionKey.OP_READ
250 | SelectionKey.OP_WRITE
251 | SelectionKey.OP_CONNECT);
252 }
253
254
255 // -- Socket-specific operations --
256
257 /**
258 * @throws ConnectionPendingException
259 * If a non-blocking connect operation is already in progress on
260 * this channel
261 * @throws AlreadyBoundException {@inheritDoc}
262 * @throws UnsupportedAddressTypeException {@inheritDoc}
263 * @throws ClosedChannelException {@inheritDoc}
264 * @throws IOException {@inheritDoc}
265 * @throws SecurityException
266 * If a security manager has been installed and its
267 * {@link SecurityManager#checkListen checkListen} method denies
268 * the operation
269 *
270 * @since 1.7
271 */
272 @Override
273 public abstract SocketChannel bind(SocketAddress local)
274 throws IOException;
275
276 /**
277 * @throws UnsupportedOperationException {@inheritDoc}
278 * @throws IllegalArgumentException {@inheritDoc}
279 * @throws ClosedChannelException {@inheritDoc}
280 * @throws IOException {@inheritDoc}
281 *
282 * @since 1.7
283 */
284 @Override
285 public abstract <T> SocketChannel setOption(SocketOption<T> name, T value)
286 throws IOException;
287
288 /**
312 * channel will throw {@link ClosedChannelException}. If the output side of
313 * the connection is already shutdown then invoking this method has no
314 * effect.
315 *
316 * @return The channel
317 *
318 * @throws NotYetConnectedException
319 * If this channel is not yet connected
320 * @throws ClosedChannelException
321 * If this channel is closed
322 * @throws IOException
323 * If some other I/O error occurs
324 *
325 * @since 1.7
326 */
327 public abstract SocketChannel shutdownOutput() throws IOException;
328
329 /**
330 * Retrieves a socket associated with this channel.
331 *
332 * <p> The returned object will not declare any public methods that are not
333 * declared in the {@link java.net.Socket} class. </p>
334 *
335 * @return A socket associated with this channel
336 */
337 public abstract Socket socket();
338
339 /**
340 * Tells whether or not this channel's network socket is connected.
341 *
342 * @return {@code true} if, and only if, this channel's network socket
343 * is {@link #isOpen open} and connected
344 */
345 public abstract boolean isConnected();
346
347 /**
348 * Tells whether or not a connection operation is in progress on this
349 * channel.
350 *
351 * @return {@code true} if, and only if, a connection operation has been
352 * initiated on this channel but not yet completed by invoking the
353 * {@link #finishConnect finishConnect} method
354 */
355 public abstract boolean isConnectionPending();
356
357 /**
358 * Connects this channel's socket.
359 *
360 * <p> If this channel is in non-blocking mode then an invocation of this
361 * method initiates a non-blocking connection operation. If the connection
362 * is established immediately, as can happen with a local connection, then
363 * this method returns {@code true}. Otherwise this method returns
364 * {@code false} and the connection operation must later be completed by
365 * invoking the {@link #finishConnect finishConnect} method.
366 *
367 * <p> If this channel is in blocking mode then an invocation of this
368 * method will block until the connection is established or an I/O error
369 * occurs.
370 *
371 * <p> This method performs exactly the same security checks as the {@link
372 * java.net.Socket} class. That is, if a security manager has been
373 * installed then this method verifies that its {@link
374 * java.lang.SecurityManager#checkConnect checkConnect} method permits
375 * connecting to the address and port number of the given remote endpoint.
376 *
377 * <p> This method may be invoked at any time. If a read or write
378 * operation upon this channel is invoked while an invocation of this
379 * method is in progress then that operation will first block until this
380 * invocation is complete. If a connection attempt is initiated but fails,
381 * that is, if an invocation of this method throws a checked exception,
382 * then the channel will be closed. </p>
383 *
384 * @param remote
385 * The remote address to which this channel is to be connected
386 *
387 * @return {@code true} if a connection was established,
388 * {@code false} if this channel is in non-blocking mode
389 * and the connection operation is in progress
390 *
391 * @throws AlreadyConnectedException
392 * If this channel is already connected
393 *
394 * @throws ConnectionPendingException
395 * If a non-blocking connection operation is already in progress
396 * on this channel
397 *
398 * @throws ClosedChannelException
399 * If this channel is closed
400 *
401 * @throws AsynchronousCloseException
402 * If another thread closes this channel
403 * while the connect operation is in progress
404 *
405 * @throws ClosedByInterruptException
406 * If another thread interrupts the current thread
407 * while the connect operation is in progress, thereby
408 * closing the channel and setting the current thread's
409 * interrupt status
410 *
411 * @throws UnresolvedAddressException
412 * If the given remote address is not fully resolved
413 *
414 * @throws UnsupportedAddressTypeException
415 * If the type of the given remote address is not supported
416 *
417 * @throws SecurityException
418 * If a security manager has been installed
419 * and it does not permit access to the given remote endpoint
420 *
421 * @throws IOException
422 * If some other I/O error occurs
423 */
424 public abstract boolean connect(SocketAddress remote) throws IOException;
425
426 /**
427 * Finishes the process of connecting a socket channel.
428 *
429 * <p> A non-blocking connection operation is initiated by placing a socket
430 * channel in non-blocking mode and then invoking its {@link #connect
431 * connect} method. Once the connection is established, or the attempt has
432 * failed, the socket channel will become connectable and this method may
460 * If this channel is closed
461 *
462 * @throws AsynchronousCloseException
463 * If another thread closes this channel
464 * while the connect operation is in progress
465 *
466 * @throws ClosedByInterruptException
467 * If another thread interrupts the current thread
468 * while the connect operation is in progress, thereby
469 * closing the channel and setting the current thread's
470 * interrupt status
471 *
472 * @throws IOException
473 * If some other I/O error occurs
474 */
475 public abstract boolean finishConnect() throws IOException;
476
477 /**
478 * Returns the remote address to which this channel's socket is connected.
479 *
480 * <p> Where the channel is bound and connected to an Internet Protocol
481 * socket address then the return value from this method is of type {@link
482 * java.net.InetSocketAddress}.
483 *
484 * @return The remote address; {@code null} if the channel's socket is not
485 * connected
486 *
487 * @throws ClosedChannelException
488 * If the channel is closed
489 * @throws IOException
490 * If an I/O error occurs
491 *
492 * @since 1.7
493 */
494 public abstract SocketAddress getRemoteAddress() throws IOException;
495
496 // -- ByteChannel operations --
497
498 /**
499 * @throws NotYetConnectedException
500 * If this channel is not yet connected
501 */
502 public abstract int read(ByteBuffer dst) throws IOException;
522 */
523 public abstract int write(ByteBuffer src) throws IOException;
524
525 /**
526 * @throws NotYetConnectedException
527 * If this channel is not yet connected
528 */
529 public abstract long write(ByteBuffer[] srcs, int offset, int length)
530 throws IOException;
531
532 /**
533 * @throws NotYetConnectedException
534 * If this channel is not yet connected
535 */
536 public final long write(ByteBuffer[] srcs) throws IOException {
537 return write(srcs, 0, srcs.length);
538 }
539
540 /**
541 * {@inheritDoc}
542 * <p>
543 * If there is a security manager set, its {@code checkConnect} method is
544 * called with the local address and {@code -1} as its arguments to see
545 * if the operation is allowed. If the operation is not allowed,
546 * a {@code SocketAddress} representing the
547 * {@link java.net.InetAddress#getLoopbackAddress loopback} address and the
548 * local port of the channel's socket is returned.
549 *
550 * @return The {@code SocketAddress} that the socket is bound to, or the
551 * {@code SocketAddress} representing the loopback address if
552 * denied by the security manager, or {@code null} if the
553 * channel's socket is not bound
554 *
555 * @throws ClosedChannelException {@inheritDoc}
556 * @throws IOException {@inheritDoc}
557 */
558 @Override
559 public abstract SocketAddress getLocalAddress() throws IOException;
560
561 }
|
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
26 package java.nio.channels;
27
28 import java.io.IOException;
29 import java.net.InetSocketAddress;
30 import java.net.NetPermission;
31 import java.net.ProtocolFamily;
32 import java.net.StandardProtocolFamily;
33 import java.net.Socket;
34 import java.net.SocketOption;
35 import java.net.SocketAddress;
36 import java.net.UnixDomainSocketAddress;
37 import java.nio.ByteBuffer;
38 import java.nio.channels.spi.AbstractSelectableChannel;
39 import java.nio.channels.spi.SelectorProvider;
40 import static java.util.Objects.requireNonNull;
41
42 /**
43 * A selectable channel for stream-oriented connecting sockets.
44 *
45 * <p> A socket channel is created by invoking one of the {@code open} methods of
46 * this class. The no-arg {@link #open() open} method opens a socket channel
47 * for an <i>Internet protocol</i> socket. The {@link #open(ProtocolFamily)}
48 * method is used to open a socket channel for a socket of a specified protocol
49 * family. It is not possible to create a channel for an arbitrary, pre-existing
50 * socket. A newly-created socket channel is open but not yet connected. An
51 * attempt to invoke an I/O operation upon an unconnected channel will cause a
52 * {@link NotYetConnectedException} to be thrown. A socket channel can be
53 * connected by invoking its {@link #connect connect} method; once connected,
54 * a socket channel remains connected until it is closed. Whether or not a
55 * socket channel is connected may be determined by invoking its {@link #isConnected()
56 * isConnected} method.
57 *
58 * <p> Socket channels support <i>non-blocking connection:</i> A socket
59 * channel may be created and the process of establishing the link to the
60 * remote socket may be initiated via the {@link #connect connect} method for
61 * later completion by the {@link #finishConnect finishConnect} method.
62 * Whether or not a connection operation is in progress may be determined by
63 * invoking the {@link #isConnectionPending isConnectionPending} method.
64 *
65 * <p> Socket channels support <i>asynchronous shutdown</i>, which is similar
66 * to the asynchronous close operation specified in the {@link Channel} class.
67 * If the input side of a socket is shut down by one thread while another
68 * thread is blocked in a read operation on the socket's channel, then the read
69 * operation in the blocked thread will complete without reading any bytes and
70 * will return {@code -1}. If the output side of a socket is shut down by one
71 * thread while another thread is blocked in a write operation on the socket's
72 * channel, then the blocked thread will receive an {@link
73 * AsynchronousCloseException}.
74 *
75 * <p> Socket options are configured using the {@link #setOption(SocketOption,Object)
76 * setOption} method. Socket channels for <i>Internet protocol</i> sockets support
77 * following options:
78 * <blockquote>
79 * <table class="striped">
80 * <caption style="display:none">Socket options</caption>
81 * <thead>
82 * <tr>
83 * <th scope="col">Option Name</th>
84 * <th scope="col">Description</th>
85 * </tr>
86 * </thead>
87 * <tbody>
88 * <tr>
89 * <th scope="row"> {@link java.net.StandardSocketOptions#SO_SNDBUF SO_SNDBUF} </th>
90 * <td> The size of the socket send buffer </td>
91 * </tr>
92 * <tr>
93 * <th scope="row"> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </th>
94 * <td> The size of the socket receive buffer </td>
95 * </tr>
96 * <tr>
97 * <th scope="row"> {@link java.net.StandardSocketOptions#SO_KEEPALIVE SO_KEEPALIVE} </th>
98 * <td> Keep connection alive </td>
99 * </tr>
100 * <tr>
101 * <th scope="row"> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </th>
102 * <td> Re-use address </td>
103 * </tr>
104 * <tr>
105 * <th scope="row"> {@link java.net.StandardSocketOptions#SO_LINGER SO_LINGER} </th>
106 * <td> Linger on close if data is present (when configured in blocking mode
107 * only) </td>
108 * </tr>
109 * <tr>
110 * <th scope="row"> {@link java.net.StandardSocketOptions#TCP_NODELAY TCP_NODELAY} </th>
111 * <td> Disable the Nagle algorithm </td>
112 * </tr>
113 * </tbody>
114 * </table>
115 * </blockquote>
116 *
117 * <p> Socket channels for <i>Unix domain</i> sockets support:
118 * <blockquote>
119 * <table class="striped">
120 * <caption style="display:none">Socket options</caption>
121 * <thead>
122 * <tr>
123 * <th scope="col">Option Name</th>
124 * <th scope="col">Description</th>
125 * </tr>
126 * </thead>
127 * <tbody>
128 * <tr>
129 * <th scope="row"> {@link java.net.StandardSocketOptions#SO_SNDBUF SO_SNDBUF} </th>
130 * <td> The size of the socket send buffer </td>
131 * </tr>
132 * <tr>
133 * <th scope="row"> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </th>
134 * <td> The size of the socket receive buffer </td>
135 * </tr>
136 * <tr>
137 * <th scope="row"> {@link java.net.StandardSocketOptions#SO_LINGER SO_LINGER} </th>
138 * <td> Linger on close if data is present (when configured in blocking mode
139 * only) </td>
140 * </tr>
141 * </tbody>
142 * </table>
143 * </blockquote>
144 *
145 * <p> Additional (implementation specific) options may also be supported.
146 *
147 * <p> Socket channels are safe for use by multiple concurrent threads. They
148 * support concurrent reading and writing, though at most one thread may be
149 * reading and at most one thread may be writing at any given time. The {@link
150 * #connect connect} and {@link #finishConnect finishConnect} methods are
151 * mutually synchronized against each other, and an attempt to initiate a read
152 * or write operation while an invocation of one of these methods is in
153 * progress will block until that invocation is complete. </p>
154 *
155 * @author Mark Reinhold
156 * @author JSR-51 Expert Group
157 * @since 1.4
158 */
159
160 public abstract class SocketChannel
161 extends AbstractSelectableChannel
162 implements ByteChannel, ScatteringByteChannel, GatheringByteChannel, NetworkChannel
163 {
164
165 /**
166 * Initializes a new instance of this class.
167 *
168 * @param provider
169 * The provider that created this channel
170 */
171 protected SocketChannel(SelectorProvider provider) {
172 super(provider);
173 }
174
175 /**
176 * Opens a socket channel for an <i>Internet protocol</i> socket.
177 *
178 * <p> The new channel is created by invoking the {@link
179 * java.nio.channels.spi.SelectorProvider#openSocketChannel
180 * openSocketChannel} method of the system-wide default {@link
181 * java.nio.channels.spi.SelectorProvider} object. </p>
182 *
183 * @return A new socket channel
184 *
185 * @throws IOException
186 * If an I/O error occurs
187 *
188 * @see <a href="../../net/doc-files/net-properties.html#Ipv4IPv6">
189 * java.net.preferIPv4Stack</a> system property
190 */
191 public static SocketChannel open() throws IOException {
192 return SelectorProvider.provider().openSocketChannel();
193 }
194
195 /**
196 * Opens a socket channel. The {@code family} parameter specifies the
197 * {@link ProtocolFamily protocol family} of the channel's socket.
198 *
199 * <p> The new channel is created by invoking the {@link
200 * java.nio.channels.spi.SelectorProvider#openSocketChannel(ProtocolFamily)
201 * openSocketChannel(ProtocolFamily)} method of the system-wide default.
202 * {@link java.nio.channels.spi.SelectorProvider} object.</p>
203 *
204 * @param family
205 * The protocol family
206 *
207 * @return A new socket channel
208 *
209 * @throws UnsupportedOperationException
210 * If the specified protocol family is not supported. For example,
211 * suppose the parameter is specified as {@link
212 * java.net.StandardProtocolFamily#INET6 StandardProtocolFamily.INET6}
213 * but IPv6 is not enabled on the platform.
214 * @throws IOException
215 * If an I/O error occurs
216 *
217 * @see <a href="../../net/doc-files/net-properties.html#Ipv4IPv6">
218 * java.net.preferIPv4Stack</a> system property
219 *
220 * @since 15
221 */
222 public static SocketChannel open(ProtocolFamily family) throws IOException {
223 return SelectorProvider.provider().openSocketChannel(requireNonNull(family));
224 }
225
226 /**
227 * Opens a socket channel and connects it to a remote address.
228 *
229 * <p> If the remote address is an {@link InetSocketAddress} then this
230 * method works as if by invoking the {@link #open()} method, invoking the
231 * {@link #connect(SocketAddress) connect} method upon the resulting socket
232 * channel, passing it {@code remote}, and then returning that channel.
233 *
234 * <p> If the remote address is a {@link UnixDomainSocketAddress} then this
235 * works by invoking the {@link #open(ProtocolFamily)} method with {@link
236 * StandardProtocolFamily#UNIX} as parameter, invoking the {@link
237 * #connect(SocketAddress) connect} method upon the resulting socket channel,
238 * passing it {@code remote}, then returning that channel. </p>
239 *
240 * @param remote
241 * The remote address to which the new channel is to be connected
242 *
243 * @return A new, and connected, socket channel
244 *
245 * @throws AsynchronousCloseException
246 * If another thread closes this channel
247 * while the connect operation is in progress
248 *
249 * @throws ClosedByInterruptException
250 * If another thread interrupts the current thread
251 * while the connect operation is in progress, thereby
252 * closing the channel and setting the current thread's
253 * interrupt status
254 *
255 * @throws UnresolvedAddressException
256 * If the given remote address is an InetSocketAddress that is not fully
257 * resolved
258 *
259 * @throws UnsupportedAddressTypeException
260 * If the type of the given remote address is not supported
261 *
262 * @throws SecurityException
263 * If a security manager has been installed
264 * and it does not permit access to the given remote endpoint
265 *
266 * @throws IOException
267 * If some other I/O error occurs
268 *
269 * @see <a href="../../net/doc-files/net-properties.html#Ipv4IPv6">
270 * java.net.preferIPv4Stack</a> system property
271 */
272 public static SocketChannel open(SocketAddress remote)
273 throws IOException
274 {
275 SocketChannel sc;
276 if (remote instanceof InetSocketAddress)
277 sc = open();
278 else if (remote instanceof UnixDomainSocketAddress)
279 sc = open(StandardProtocolFamily.UNIX);
280 else
281 throw new UnsupportedAddressTypeException();
282
283 try {
284 sc.connect(remote);
285 } catch (Throwable x) {
286 try {
287 sc.close();
288 } catch (Throwable suppressed) {
289 x.addSuppressed(suppressed);
290 }
291 throw x;
292 }
293 assert sc.isConnected();
294 return sc;
295 }
296
297 /**
298 * Returns an operation set identifying this channel's supported
299 * operations.
300 *
301 * <p> Socket channels support connecting, reading, and writing, so this
302 * method returns {@code (}{@link SelectionKey#OP_CONNECT}
303 * {@code |} {@link SelectionKey#OP_READ} {@code |} {@link
304 * SelectionKey#OP_WRITE}{@code )}.
305 *
306 * @return The valid-operation set
307 */
308 public final int validOps() {
309 return (SelectionKey.OP_READ
310 | SelectionKey.OP_WRITE
311 | SelectionKey.OP_CONNECT);
312 }
313
314
315 // -- Socket-specific operations --
316
317 /**
318 * Binds the channel's socket to a local address.
319 *
320 * <p> This method is used to establish an association between the socket
321 * and a local address. For <i>Internet Protocol</i> sockets, once an
322 * association is established then the socket remains bound until the
323 * channel is closed. If the {@code local} parameter has the value {@code
324 * null} then the socket will be bound to an address that is assigned
325 * automatically.
326 *
327 * @apiNote
328 * Binding a socket channel to a <i>Unix Domain</i> socket creates a file
329 * corresponding to the file path in the {@link UnixDomainSocketAddress}. This
330 * file persists after the channel is closed, and must be removed before
331 * another socket can bind to the same name. If a socket channel to a Unix
332 * Domain socket is <i>implicitly</i> bound by connecting it without calling
333 * bind first, then its socket is
334 * <a href="../../java/net/UnixDomainSocketAddress.html#unnamed">unnamed</a>
335 * with no corresponding socket file in the file-system. If a socket channel
336 * to a Unix Domain socket is <i>automatically</i> bound by calling {@code
337 * bind(null)} this results in an unnamed socket also.
338 *
339 * @implNote
340 * Each platform enforces an implementation specific maximum length for the
341 * name of a <i>Unix Domain</i> socket. This limitation is enforced when a
342 * channel is bound. The maximum length is typically close to and generally
343 * not less than 100 bytes.
344 *
345 * @param local The address to bind the socket, or {@code null} to bind
346 * the socket to an automatically assigned socket address
347 *
348 * @return This channel
349 *
350 * @throws ConnectionPendingException
351 * If a non-blocking connect operation is already in progress on
352 * this channel
353 * @throws AlreadyBoundException {@inheritDoc}
354 * @throws UnsupportedAddressTypeException {@inheritDoc}
355 * @throws ClosedChannelException {@inheritDoc}
356 * @throws IOException {@inheritDoc}
357 * @throws SecurityException
358 * If a security manager has been installed and its {@link
359 * SecurityManager#checkListen checkListen} method denies
360 * the operation for an <i>Internet protocol</i> socket address,
361 * or for a <i>Unix domain</i> socket address if it denies
362 * {@link NetPermission}{@code("accessUnixDomainSocket")}.
363 *
364 * @since 1.7
365 */
366 @Override
367 public abstract SocketChannel bind(SocketAddress local)
368 throws IOException;
369
370 /**
371 * @throws UnsupportedOperationException {@inheritDoc}
372 * @throws IllegalArgumentException {@inheritDoc}
373 * @throws ClosedChannelException {@inheritDoc}
374 * @throws IOException {@inheritDoc}
375 *
376 * @since 1.7
377 */
378 @Override
379 public abstract <T> SocketChannel setOption(SocketOption<T> name, T value)
380 throws IOException;
381
382 /**
406 * channel will throw {@link ClosedChannelException}. If the output side of
407 * the connection is already shutdown then invoking this method has no
408 * effect.
409 *
410 * @return The channel
411 *
412 * @throws NotYetConnectedException
413 * If this channel is not yet connected
414 * @throws ClosedChannelException
415 * If this channel is closed
416 * @throws IOException
417 * If some other I/O error occurs
418 *
419 * @since 1.7
420 */
421 public abstract SocketChannel shutdownOutput() throws IOException;
422
423 /**
424 * Retrieves a socket associated with this channel.
425 *
426 * @return A socket associated with this channel
427 *
428 * @throws UnsupportedOperationException
429 * If the channel's socket is not an <i>Internet protocol</i> socket
430 */
431 public abstract Socket socket();
432
433 /**
434 * Tells whether or not this channel's network socket is connected.
435 *
436 * @return {@code true} if, and only if, this channel's network socket
437 * is {@link #isOpen open} and connected
438 */
439 public abstract boolean isConnected();
440
441 /**
442 * Tells whether or not a connection operation is in progress on this
443 * channel.
444 *
445 * @return {@code true} if, and only if, a connection operation has been
446 * initiated on this channel but not yet completed by invoking the
447 * {@link #finishConnect finishConnect} method
448 */
449 public abstract boolean isConnectionPending();
450
451 /**
452 * Connects this channel's socket.
453 *
454 * <p> If this channel is in non-blocking mode then an invocation of this
455 * method initiates a non-blocking connection operation. If the connection
456 * is established immediately, as can happen with a local connection, then
457 * this method returns {@code true}. Otherwise this method returns
458 * {@code false} and the connection operation must later be completed by
459 * invoking the {@link #finishConnect finishConnect} method.
460 *
461 * <p> If this channel is in blocking mode then an invocation of this
462 * method will block until the connection is established or an I/O error
463 * occurs.
464 *
465 * <p> For channels to <i>Internet protocol</i> sockets, this method performs
466 * exactly the same security checks as the {@link java.net.Socket} class.
467 * That is, if a security manager has been
468 * installed then this method verifies that its {@link
469 * java.lang.SecurityManager#checkConnect checkConnect} method permits
470 * connecting to the address and port number of the given remote endpoint.
471 *
472 * <p> For channels to <i>Unix Domain</i> sockets, this method checks
473 * {@link java.net.NetPermission NetPermission}{@code
474 * ("accessUnixDomainSocket")} with the security manager's {@link
475 * SecurityManager#checkPermission(java.security.Permission)
476 * checkPermission} method.
477 *
478 * <p> This method may be invoked at any time. If a read or write
479 * operation upon this channel is invoked while an invocation of this
480 * method is in progress then that operation will first block until this
481 * invocation is complete. If a connection attempt is initiated but fails,
482 * that is, if an invocation of this method throws a checked exception,
483 * then the channel will be closed. </p>
484 *
485 * @param remote
486 * The remote address to which this channel is to be connected
487 *
488 * @return {@code true} if a connection was established,
489 * {@code false} if this channel is in non-blocking mode
490 * and the connection operation is in progress
491 *
492 * @throws AlreadyConnectedException
493 * If this channel is already connected
494 *
495 * @throws ConnectionPendingException
496 * If a non-blocking connection operation is already in progress
497 * on this channel
498 *
499 * @throws ClosedChannelException
500 * If this channel is closed
501 *
502 * @throws AsynchronousCloseException
503 * If another thread closes this channel
504 * while the connect operation is in progress
505 *
506 * @throws ClosedByInterruptException
507 * If another thread interrupts the current thread
508 * while the connect operation is in progress, thereby
509 * closing the channel and setting the current thread's
510 * interrupt status
511 *
512 * @throws UnresolvedAddressException
513 * If the given remote address is an InetSocketAddress that is not fully resolved
514 *
515 * @throws UnsupportedAddressTypeException
516 * If the type of the given remote address is not supported
517 *
518 * @throws SecurityException
519 * If a security manager has been installed
520 * and it does not permit access to the given remote endpoint
521 *
522 * @throws IOException
523 * If some other I/O error occurs
524 */
525 public abstract boolean connect(SocketAddress remote) throws IOException;
526
527 /**
528 * Finishes the process of connecting a socket channel.
529 *
530 * <p> A non-blocking connection operation is initiated by placing a socket
531 * channel in non-blocking mode and then invoking its {@link #connect
532 * connect} method. Once the connection is established, or the attempt has
533 * failed, the socket channel will become connectable and this method may
561 * If this channel is closed
562 *
563 * @throws AsynchronousCloseException
564 * If another thread closes this channel
565 * while the connect operation is in progress
566 *
567 * @throws ClosedByInterruptException
568 * If another thread interrupts the current thread
569 * while the connect operation is in progress, thereby
570 * closing the channel and setting the current thread's
571 * interrupt status
572 *
573 * @throws IOException
574 * If some other I/O error occurs
575 */
576 public abstract boolean finishConnect() throws IOException;
577
578 /**
579 * Returns the remote address to which this channel's socket is connected.
580 *
581 * <p> Where the channel's socket is bound and connected to an <i>Internet
582 * Protocol</i> socket address then the return value is of type
583 * {@link java.net.InetSocketAddress}.
584 *
585 * <p> Where the channel's socket is bound and connected to a <i>Unix Domain</i>
586 * socket address, the returned address is a {@link UnixDomainSocketAddress}.
587 *
588 * @return The remote address; {@code null} if the channel's socket is not
589 * connected
590 *
591 * @throws ClosedChannelException
592 * If the channel is closed
593 * @throws IOException
594 * If an I/O error occurs
595 *
596 * @since 1.7
597 */
598 public abstract SocketAddress getRemoteAddress() throws IOException;
599
600 // -- ByteChannel operations --
601
602 /**
603 * @throws NotYetConnectedException
604 * If this channel is not yet connected
605 */
606 public abstract int read(ByteBuffer dst) throws IOException;
626 */
627 public abstract int write(ByteBuffer src) throws IOException;
628
629 /**
630 * @throws NotYetConnectedException
631 * If this channel is not yet connected
632 */
633 public abstract long write(ByteBuffer[] srcs, int offset, int length)
634 throws IOException;
635
636 /**
637 * @throws NotYetConnectedException
638 * If this channel is not yet connected
639 */
640 public final long write(ByteBuffer[] srcs) throws IOException {
641 return write(srcs, 0, srcs.length);
642 }
643
644 /**
645 * {@inheritDoc}
646 *
647 * If there is a security manager set, its {@code checkConnect} method is
648 * called with the local address and {@code -1} as its arguments to see
649 * if the operation is allowed. If the operation is not allowed,
650 * a {@code SocketAddress} representing the
651 * {@link java.net.InetAddress#getLoopbackAddress loopback} address and the
652 * local port of the channel's socket is returned.
653 *
654 * <p> Where the channel is bound to a Unix Domain socket address, the socket
655 * address is a {@link UnixDomainSocketAddress}. If there is a security manager
656 * set, its {@link SecurityManager#checkPermission(java.security.Permission)
657 * checkPermission} method is called with {@link NetPermission}{@code
658 * ("accessUnixDomainSocket")}. If the operation is not allowed an unnamed
659 * {@link UnixDomainSocketAddress} is returned.
660 *
661 * @return The {@code SocketAddress} that the socket is bound to, or the
662 * {@code SocketAddress} representing the loopback address or empty
663 * path if denied by the security manager, or {@code null} if the
664 * channel's socket is not bound
665 *
666 * @throws ClosedChannelException {@inheritDoc}
667 * @throws IOException {@inheritDoc}
668 */
669 @Override
670 public abstract SocketAddress getLocalAddress() throws IOException;
671 }
|