src/java.base/share/classes/java/nio/channels/SocketChannel.java
branchunixdomainchannels
changeset 58801 119ac9128c1b
parent 47216 71c04702a3d5
child 58847 692de65ab293
equal deleted inserted replaced
58799:eb491334113f 58801:119ac9128c1b
     1 /*
     1 /*
     2  * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
     2  * Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     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
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     7  * published by the Free Software Foundation.  Oracle designates this
    24  */
    24  */
    25 
    25 
    26 package java.nio.channels;
    26 package java.nio.channels;
    27 
    27 
    28 import java.io.IOException;
    28 import java.io.IOException;
       
    29 import java.net.InetSocketAddress;
       
    30 import java.net.ProtocolFamily;
       
    31 import java.net.StandardProtocolFamily;
    29 import java.net.Socket;
    32 import java.net.Socket;
    30 import java.net.SocketOption;
    33 import java.net.SocketOption;
    31 import java.net.SocketAddress;
    34 import java.net.SocketAddress;
    32 import java.nio.ByteBuffer;
    35 import java.nio.ByteBuffer;
    33 import java.nio.channels.spi.AbstractSelectableChannel;
    36 import java.nio.channels.spi.AbstractSelectableChannel;
    34 import java.nio.channels.spi.SelectorProvider;
    37 import java.nio.channels.spi.SelectorProvider;
    35 
    38 
    36 /**
    39 /**
    37  * A selectable channel for stream-oriented connecting sockets.
    40  * A selectable channel for stream-oriented connecting sockets.
    38  *
    41  *
    39  * <p> A socket channel is created by invoking one of the {@link #open open}
    42  * <p> A socket channel is created by invoking one of the open methods of this class.
    40  * methods of this class.  It is not possible to create a channel for an arbitrary,
    43  * 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
    44  * 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
    45  * connected.  An attempt to invoke an I/O operation upon an unconnected
    43  * channel will cause a {@link NotYetConnectedException} to be thrown.  A
    46  * channel will cause a {@link NotYetConnectedException} to be thrown.  A
    44  * socket channel can be connected by invoking its {@link #connect connect}
    47  * socket channel can be connected by invoking its {@link #connect connect}
    45  * method; once connected, a socket channel remains connected until it is
    48  * method; once connected, a socket channel remains connected until it is
    61  * will return {@code -1}.  If the output side of a socket is shut down by one
    64  * will return {@code -1}.  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
    65  * thread while another thread is blocked in a write operation on the socket's
    63  * channel, then the blocked thread will receive an {@link
    66  * channel, then the blocked thread will receive an {@link
    64  * AsynchronousCloseException}.
    67  * AsynchronousCloseException}.
    65  *
    68  *
       
    69  * <p>Two kinds of socket channel are supported: <i>IP</i> (Internet Protocol) and
       
    70  * <i>unix domain</i> depending on which open method is used to create them and which
       
    71  * subtype of {@link SocketAddress} that they support for local and remote addresses.
       
    72  * <i>IP</i> channels are created using {@link #open()}. They use {@link
       
    73  * InetSocketAddress} addresses and support both IPv4 and IPv6 TCP/IP.
       
    74  * <i>unix domain</i> channels are created using {@link #open(ProtocolFamily)}
       
    75  * with the family parameter set to {@link StandardProtocolFamily#UNIX}.
       
    76  * They use {@link UnixDomainSocketAddress}es and also
       
    77  * do not support the {@link #socket()} method.
       
    78  *
    66  * <p> Socket options are configured using the {@link #setOption(SocketOption,Object)
    79  * <p> Socket options are configured using the {@link #setOption(SocketOption,Object)
    67  * setOption} method. Socket channels support the following options:
    80  * setOption} method. <i>IP</i> socket channels support the following options:
    68  * <blockquote>
    81  * <blockquote>
    69  * <table class="striped">
    82  * <table class="striped">
    70  * <caption style="display:none">Socket options</caption>
    83  * <caption style="display:none">Socket options</caption>
    71  * <thead>
    84  * <thead>
    72  *   <tr>
    85  *   <tr>
   101  *     <td> Disable the Nagle algorithm </td>
   114  *     <td> Disable the Nagle algorithm </td>
   102  *   </tr>
   115  *   </tr>
   103  * </tbody>
   116  * </tbody>
   104  * </table>
   117  * </table>
   105  * </blockquote>
   118  * </blockquote>
       
   119  *
   106  * Additional (implementation specific) options may also be supported.
   120  * Additional (implementation specific) options may also be supported.
   107  *
   121  *
   108  * <p> Socket channels are safe for use by multiple concurrent threads.  They
   122  * <p> Socket channels are safe for use by multiple concurrent threads.  They
   109  * support concurrent reading and writing, though at most one thread may be
   123  * support concurrent reading and writing, though at most one thread may be
   110  * reading and at most one thread may be writing at any given time.  The {@link
   124  * reading and at most one thread may be writing at any given time.  The {@link
   111  * #connect connect} and {@link #finishConnect finishConnect} methods are
   125  * #connect connect} and {@link #finishConnect finishConnect} methods are
   112  * mutually synchronized against each other, and an attempt to initiate a read
   126  * mutually synchronized against each other, and an attempt to initiate a read
   113  * or write operation while an invocation of one of these methods is in
   127  * or write operation while an invocation of one of these methods is in
   114  * progress will block until that invocation is complete.  </p>
   128  * progress will block until that invocation is complete.  </p>
   115  *
   129  *
       
   130  * <p><i>Unix domain</i> channels support a subset of the options listed above.
       
   131  *
   116  * @author Mark Reinhold
   132  * @author Mark Reinhold
   117  * @author JSR-51 Expert Group
   133  * @author JSR-51 Expert Group
   118  * @since 1.4
   134  * @since 1.4
   119  */
   135  */
   120 
   136 
   122     extends AbstractSelectableChannel
   138     extends AbstractSelectableChannel
   123     implements ByteChannel, ScatteringByteChannel, GatheringByteChannel, NetworkChannel
   139     implements ByteChannel, ScatteringByteChannel, GatheringByteChannel, NetworkChannel
   124 {
   140 {
   125 
   141 
   126     /**
   142     /**
   127      * Initializes a new instance of this class.
   143      * Initializes a new <i>IP</i> instance of this class.
   128      *
   144      *
   129      * @param  provider
   145      * @param  provider
   130      *         The provider that created this channel
   146      *         The provider that created this channel
   131      */
   147      */
   132     protected SocketChannel(SelectorProvider provider) {
   148     protected SocketChannel(SelectorProvider provider) {
   133         super(provider);
   149         super(provider);
   134     }
   150     }
   135 
   151 
   136     /**
   152     /**
   137      * Opens a socket channel.
   153      * Opens an <i>IP</i> socket channel.
   138      *
   154      *
   139      * <p> The new channel is created by invoking the {@link
   155      * <p> The new channel is created by invoking the {@link
   140      * java.nio.channels.spi.SelectorProvider#openSocketChannel
   156      * java.nio.channels.spi.SelectorProvider#openSocketChannel
   141      * openSocketChannel} method of the system-wide default {@link
   157      * openSocketChannel} method of the system-wide default {@link
   142      * java.nio.channels.spi.SelectorProvider} object.  </p>
   158      * java.nio.channels.spi.SelectorProvider} object.  </p>
   149     public static SocketChannel open() throws IOException {
   165     public static SocketChannel open() throws IOException {
   150         return SelectorProvider.provider().openSocketChannel();
   166         return SelectorProvider.provider().openSocketChannel();
   151     }
   167     }
   152 
   168 
   153     /**
   169     /**
       
   170      * Returns a {@link SocketChannel} of the given {@link ProtocolFamily}.
       
   171      *
       
   172      * @param family the protocol family
       
   173      *
       
   174      * @return a SocketChannel
       
   175      *
       
   176      * @throws IOException if an I/O error occurs
       
   177      * @throws UnsupportedAddressTypeException if the protocol family is not supported
       
   178      * @since 14
       
   179      */
       
   180     public static SocketChannel open(ProtocolFamily family) throws IOException {
       
   181         return SelectorProvider.provider().openSocketChannel(family);
       
   182     }
       
   183 
       
   184     /**
   154      * Opens a socket channel and connects it to a remote address.
   185      * Opens a socket channel and connects it to a remote address.
   155      *
   186      * Depending on the type of {@link SocketAddress} supplied, the returned object
   156      * <p> This convenience method works as if by invoking the {@link #open()}
   187      * is an <i>IP</i> or <i>unix domain</i> channel.
       
   188      *
       
   189      * <p> For {@link InetSocketAddress}es this convenience method works as if by invoking the {@link #open()}
   157      * method, invoking the {@link #connect(SocketAddress) connect} method upon
   190      * method, invoking the {@link #connect(SocketAddress) connect} method upon
       
   191      * the resulting socket channel, passing it {@code remote}, and then
       
   192      * returning that channel.  </p>
       
   193      *
       
   194      * <p> For {@link UnixDomainSocketAddress}es it works as if by invoking the {@link
       
   195      * #open(ProtocolFamily)} method with {@link StandardProtocolFamily#UNIX} as parameter,
       
   196      * invoking the {@link #connect(SocketAddress) connect} method upon
   158      * the resulting socket channel, passing it {@code remote}, and then
   197      * the resulting socket channel, passing it {@code remote}, and then
   159      * returning that channel.  </p>
   198      * returning that channel.  </p>
   160      *
   199      *
   161      * @param  remote
   200      * @param  remote
   162      *         The remote address to which the new channel is to be connected
   201      *         The remote address to which the new channel is to be connected
   172      *          while the connect operation is in progress, thereby
   211      *          while the connect operation is in progress, thereby
   173      *          closing the channel and setting the current thread's
   212      *          closing the channel and setting the current thread's
   174      *          interrupt status
   213      *          interrupt status
   175      *
   214      *
   176      * @throws  UnresolvedAddressException
   215      * @throws  UnresolvedAddressException
   177      *          If the given remote address is not fully resolved
   216      *          If the given remote is an InetSocketAddress that is not fully resolved
   178      *
   217      *
   179      * @throws  UnsupportedAddressTypeException
   218      * @throws  UnsupportedAddressTypeException
   180      *          If the type of the given remote address is not supported
   219      *          If the type of the given remote address is not supported
   181      *
   220      *
   182      * @throws  SecurityException
   221      * @throws  SecurityException
   187      *          If some other I/O error occurs
   226      *          If some other I/O error occurs
   188      */
   227      */
   189     public static SocketChannel open(SocketAddress remote)
   228     public static SocketChannel open(SocketAddress remote)
   190         throws IOException
   229         throws IOException
   191     {
   230     {
   192         SocketChannel sc = open();
   231         SocketChannel sc;
       
   232         if (remote instanceof InetSocketAddress)
       
   233             sc = open();
       
   234         else if (remote instanceof UnixDomainSocketAddress)
       
   235             sc = open(StandardProtocolFamily.UNIX);
       
   236         else
       
   237             throw new UnsupportedAddressTypeException();
       
   238 
   193         try {
   239         try {
   194             sc.connect(remote);
   240             sc.connect(remote);
   195         } catch (Throwable x) {
   241         } catch (Throwable x) {
   196             try {
   242             try {
   197                 sc.close();
   243                 sc.close();
   223 
   269 
   224 
   270 
   225     // -- Socket-specific operations --
   271     // -- Socket-specific operations --
   226 
   272 
   227     /**
   273     /**
       
   274      * {@inheritDoc}
       
   275      *
       
   276      * <p> Note, for <i>Unix domain</i> channels, a file is created in the file-system
       
   277      * with the same name as this channel's bound address. This file persists after
       
   278      * the channel is closed, and must be removed before another channel can bind
       
   279      * to the same name.
       
   280      *
   228      * @throws  ConnectionPendingException
   281      * @throws  ConnectionPendingException
   229      *          If a non-blocking connect operation is already in progress on
   282      *          If a non-blocking connect operation is already in progress on
   230      *          this channel
   283      *          this channel
   231      * @throws  AlreadyBoundException               {@inheritDoc}
   284      * @throws  AlreadyBoundException               {@inheritDoc}
   232      * @throws  UnsupportedAddressTypeException     {@inheritDoc}
   285      * @throws  UnsupportedAddressTypeException     {@inheritDoc}
   233      * @throws  ClosedChannelException              {@inheritDoc}
   286      * @throws  ClosedChannelException              {@inheritDoc}
   234      * @throws  IOException                         {@inheritDoc}
   287      * @throws  IOException                         {@inheritDoc}
   235      * @throws  SecurityException
   288      * @throws  SecurityException
   236      *          If a security manager has been installed and its
   289      *          If a security manager has been installed and its
   237      *          {@link SecurityManager#checkListen checkListen} method denies
   290      *          {@link SecurityManager#checkListen checkListen} method denies
   238      *          the operation
   291      *          the operation for <i>IP</i> channels or for <i>unix domain</i>
       
   292      *          channels, if the security manager denies "read" or "write"
       
   293      *          {@link FilePermission} for the local path.
   239      *
   294      *
   240      * @since 1.7
   295      * @since 1.7
   241      */
   296      */
   242     @Override
   297     @Override
   243     public abstract SocketChannel bind(SocketAddress local)
   298     public abstract SocketChannel bind(SocketAddress local)
   295      * @since 1.7
   350      * @since 1.7
   296      */
   351      */
   297     public abstract SocketChannel shutdownOutput() throws IOException;
   352     public abstract SocketChannel shutdownOutput() throws IOException;
   298 
   353 
   299     /**
   354     /**
   300      * Retrieves a socket associated with this channel.
   355      * Retrieves a socket associated with this channel if it is an <i>IP</i>
       
   356      * channel. The operation is not supported for <i>unix domain</i> channels.
   301      *
   357      *
   302      * <p> The returned object will not declare any public methods that are not
   358      * <p> The returned object will not declare any public methods that are not
   303      * declared in the {@link java.net.Socket} class.  </p>
   359      * declared in the {@link java.net.Socket} class.  </p>
   304      *
   360      *
   305      * @return  A socket associated with this channel
   361      * @return  A socket associated with this channel
       
   362      * @throws UnsupportedOperationException is this is a Unix domain channel
   306      */
   363      */
   307     public abstract Socket socket();
   364     public abstract Socket socket();
   308 
   365 
   309     /**
   366     /**
   310      * Tells whether or not this channel's network socket is connected.
   367      * Tells whether or not this channel's network socket is connected.
   336      *
   393      *
   337      * <p> If this channel is in blocking mode then an invocation of this
   394      * <p> If this channel is in blocking mode then an invocation of this
   338      * method will block until the connection is established or an I/O error
   395      * method will block until the connection is established or an I/O error
   339      * occurs.
   396      * occurs.
   340      *
   397      *
   341      * <p> This method performs exactly the same security checks as the {@link
   398      * <p> For <i>IP</i> channels, this method performs exactly the same security checks
   342      * java.net.Socket} class.  That is, if a security manager has been
   399      * as the {@link java.net.Socket} class.  That is, if a security manager has been
   343      * installed then this method verifies that its {@link
   400      * installed then this method verifies that its {@link
   344      * java.lang.SecurityManager#checkConnect checkConnect} method permits
   401      * java.lang.SecurityManager#checkConnect checkConnect} method permits
   345      * connecting to the address and port number of the given remote endpoint.
   402      * connecting to the address and port number of the given remote endpoint.
       
   403      *
       
   404      * <p> For <i>unix domain</i> channels, this method performs a security
       
   405      * manager {@link SecurityManager#checkPermission(Permission)} using
       
   406      * a {@link java.io.FilePermission} constructed with the path from the
       
   407      * destination address and "read,write" as the actions.
   346      *
   408      *
   347      * <p> This method may be invoked at any time.  If a read or write
   409      * <p> This method may be invoked at any time.  If a read or write
   348      * operation upon this channel is invoked while an invocation of this
   410      * operation upon this channel is invoked while an invocation of this
   349      * method is in progress then that operation will first block until this
   411      * method is in progress then that operation will first block until this
   350      * invocation is complete.  If a connection attempt is initiated but fails,
   412      * invocation is complete.  If a connection attempt is initiated but fails,
   377      *          while the connect operation is in progress, thereby
   439      *          while the connect operation is in progress, thereby
   378      *          closing the channel and setting the current thread's
   440      *          closing the channel and setting the current thread's
   379      *          interrupt status
   441      *          interrupt status
   380      *
   442      *
   381      * @throws  UnresolvedAddressException
   443      * @throws  UnresolvedAddressException
   382      *          If the given remote address is not fully resolved
   444      *          If the given remote address is an InetSocketAddress which is not fully resolved
   383      *
   445      *
   384      * @throws  UnsupportedAddressTypeException
   446      * @throws  UnsupportedAddressTypeException
   385      *          If the type of the given remote address is not supported
   447      *          If the type of the given remote address is not supported
   386      *
   448      *
   387      * @throws  SecurityException
   449      * @throws  SecurityException
   449      *
   511      *
   450      * <p> Where the channel is bound and connected to an Internet Protocol
   512      * <p> Where the channel is bound and connected to an Internet Protocol
   451      * socket address then the return value from this method is of type {@link
   513      * socket address then the return value from this method is of type {@link
   452      * java.net.InetSocketAddress}.
   514      * java.net.InetSocketAddress}.
   453      *
   515      *
       
   516      * <p> Where the channel is bound and connected to a <i>Unix domain</i>
       
   517      * address, the returned address is a {@link UnixDomainSocketAddress}
       
   518      *
   454      * @return  The remote address; {@code null} if the channel's socket is not
   519      * @return  The remote address; {@code null} if the channel's socket is not
   455      *          connected
   520      *          connected
   456      *
   521      *
   457      * @throws  ClosedChannelException
   522      * @throws  ClosedChannelException
   458      *          If the channel is closed
   523      *          If the channel is closed
   508     }
   573     }
   509 
   574 
   510     /**
   575     /**
   511      * {@inheritDoc}
   576      * {@inheritDoc}
   512      * <p>
   577      * <p>
   513      * If there is a security manager set, its {@code checkConnect} method is
   578      * If there is a security manager set and this is an <i>IP</i> channel,
       
   579      * {@code checkConnect} method is
   514      * called with the local address and {@code -1} as its arguments to see
   580      * called with the local address and {@code -1} as its arguments to see
   515      * if the operation is allowed. If the operation is not allowed,
   581      * if the operation is allowed. If the operation is not allowed,
   516      * a {@code SocketAddress} representing the
   582      * a {@code SocketAddress} representing the
   517      * {@link java.net.InetAddress#getLoopbackAddress loopback} address and the
   583      * {@link java.net.InetAddress#getLoopbackAddress loopback} address and the
   518      * local port of the channel's socket is returned.
   584      * local port of the channel's socket is returned.
       
   585      * <p>
       
   586      * If there is a security manager set and this is an <i>unix domain</i> channel,
       
   587      * then this returns a {@link UnixDomainSocketAddress} corresponding to the
       
   588      * bound address.
   519      *
   589      *
   520      * @return  The {@code SocketAddress} that the socket is bound to, or the
   590      * @return  The {@code SocketAddress} that the socket is bound to, or the
   521      *          {@code SocketAddress} representing the loopback address if
   591      *          {@code SocketAddress} representing the loopback address if
   522      *          denied by the security manager, or {@code null} if the
   592      *          denied by the security manager, or {@code null} if the
   523      *          channel's socket is not bound
   593      *          channel's socket is not bound
   525      * @throws  ClosedChannelException     {@inheritDoc}
   595      * @throws  ClosedChannelException     {@inheritDoc}
   526      * @throws  IOException                {@inheritDoc}
   596      * @throws  IOException                {@inheritDoc}
   527      */
   597      */
   528     @Override
   598     @Override
   529     public abstract SocketAddress getLocalAddress() throws IOException;
   599     public abstract SocketAddress getLocalAddress() throws IOException;
   530 
       
   531 }
   600 }