< prev index next >

src/java.base/share/classes/java/net/Socket.java

Print this page

  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.net;
  27 
  28 import sun.security.util.SecurityConstants;
  29 
  30 import java.io.InputStream;

  31 import java.io.OutputStream;
  32 import java.io.IOException;
  33 import java.lang.invoke.MethodHandles;
  34 import java.lang.invoke.VarHandle;
  35 import java.nio.channels.SocketChannel;
  36 import java.util.Objects;
  37 import java.util.Set;
  38 import java.util.Collections;
  39 
  40 /**
  41  * This class implements client sockets (also called just
  42  * "sockets"). A socket is an endpoint for communication
  43  * between two machines.
  44  * <p>
  45  * The actual work of the socket is performed by an instance of the
  46  * {@code SocketImpl} class.
  47  *
  48  * <p> The {@code Socket} class defines convenience
  49  * methods to set and get several socket options. This class also
  50  * defines the {@link #setOption(SocketOption, Object) setOption}

 553         }
 554     }
 555 
 556     /**
 557      * Get the {@code SocketImpl} attached to this socket, creating
 558      * it if necessary.
 559      *
 560      * @return  the {@code SocketImpl} attached to that ServerSocket.
 561      * @throws SocketException if creation fails
 562      * @since 1.4
 563      */
 564     SocketImpl getImpl() throws SocketException {
 565         if (!created)
 566             createImpl(true);
 567         return impl;
 568     }
 569 
 570     /**
 571      * Connects this socket to the server.
 572      *





 573      * @param   endpoint the {@code SocketAddress}
 574      * @throws  IOException if an error occurs during the connection
 575      * @throws  java.nio.channels.IllegalBlockingModeException
 576      *          if this socket has an associated channel,
 577      *          and the channel is in non-blocking mode
 578      * @throws  IllegalArgumentException if endpoint is null or is a
 579      *          SocketAddress subclass not supported by this socket
 580      * @since 1.4
 581      */
 582     public void connect(SocketAddress endpoint) throws IOException {
 583         connect(endpoint, 0);
 584     }
 585 
 586     /**
 587      * Connects this socket to the server with a specified timeout value.
 588      * A timeout of zero is interpreted as an infinite timeout. The connection
 589      * will then block until established or an error occurs.
 590      *





 591      * @param   endpoint the {@code SocketAddress}
 592      * @param   timeout  the timeout value to be used in milliseconds.
 593      * @throws  IOException if an error occurs during the connection
 594      * @throws  SocketTimeoutException if timeout expires before connecting
 595      * @throws  java.nio.channels.IllegalBlockingModeException
 596      *          if this socket has an associated channel,
 597      *          and the channel is in non-blocking mode
 598      * @throws  IllegalArgumentException if endpoint is null or is a
 599      *          SocketAddress subclass not supported by this socket, or
 600      *          if {@code timeout} is negative
 601      * @since 1.4
 602      */
 603     public void connect(SocketAddress endpoint, int timeout) throws IOException {
 604         if (endpoint == null)
 605             throw new IllegalArgumentException("connect: The address can't be null");
 606 
 607         if (timeout < 0)
 608           throw new IllegalArgumentException("connect: timeout can't be negative");
 609 
 610         if (isClosed())

 613         if (isConnected())
 614             throw new SocketException("already connected");
 615 
 616         if (!(endpoint instanceof InetSocketAddress epoint))
 617             throw new IllegalArgumentException("Unsupported address type");
 618 
 619         InetAddress addr = epoint.getAddress ();
 620         int port = epoint.getPort();
 621         checkAddress(addr, "connect");
 622 
 623         @SuppressWarnings("removal")
 624         SecurityManager security = System.getSecurityManager();
 625         if (security != null) {
 626             if (epoint.isUnresolved())
 627                 security.checkConnect(epoint.getHostName(), port);
 628             else
 629                 security.checkConnect(addr.getHostAddress(), port);
 630         }
 631         if (!created)
 632             createImpl(true);
 633         impl.connect(epoint, timeout);











 634         connected = true;
 635         /*
 636          * If the socket was not bound before the connect, it is now because
 637          * the kernel will have picked an ephemeral port & a local address
 638          */
 639         bound = true;
 640     }
 641 
 642     /**
 643      * Binds the socket to a local address.
 644      * <P>
 645      * If the address is {@code null}, then the system will pick up
 646      * an ephemeral port and a valid local address to bind the socket.
 647      *
 648      * @param   bindpoint the {@code SocketAddress} to bind to
 649      * @throws  IOException if the bind operation fails, or if the socket
 650      *                     is already bound.
 651      * @throws  IllegalArgumentException if bindpoint is a
 652      *          SocketAddress subclass not supported by this socket
 653      * @throws  SecurityException  if a security manager exists and its

 894      *
 895      * <ul>
 896      *
 897      *   <li><p>The network software may discard bytes that are buffered
 898      *   by the socket. Bytes that aren't discarded by the network
 899      *   software can be read using {@link java.io.InputStream#read read}.
 900      *
 901      *   <li><p>If there are no bytes buffered on the socket, or all
 902      *   buffered bytes have been consumed by
 903      *   {@link java.io.InputStream#read read}, then all subsequent
 904      *   calls to {@link java.io.InputStream#read read} will throw an
 905      *   {@link java.io.IOException IOException}.
 906      *
 907      *   <li><p>If there are no bytes buffered on the socket, and the
 908      *   socket has not been closed using {@link #close close}, then
 909      *   {@link java.io.InputStream#available available} will
 910      *   return {@code 0}.
 911      *
 912      * </ul>
 913      *





 914      * <p> Closing the returned {@link java.io.InputStream InputStream}
 915      * will close the associated socket.
 916      *
 917      * @return     an input stream for reading bytes from this socket.
 918      * @throws     IOException  if an I/O error occurs when creating the
 919      *             input stream, the socket is closed, the socket is
 920      *             not connected, or the socket input has been shutdown
 921      *             using {@link #shutdownInput()}
 922      *
 923      * @revised 1.4
 924      */
 925     public InputStream getInputStream() throws IOException {
 926         if (isClosed())
 927             throw new SocketException("Socket is closed");
 928         if (!isConnected())
 929             throw new SocketException("Socket is not connected");
 930         if (isInputShutdown())
 931             throw new SocketException("Socket input is shutdown");
 932         InputStream in = this.in;
 933         if (in == null) {
 934             // wrap the input stream so that the close method closes this socket
 935             in = new SocketInputStream(this, impl.getInputStream());
 936             if (!IN.compareAndSet(this, null, in)) {
 937                 in = this.in;
 938             }
 939         }
 940         return in;
 941     }
 942 
 943     /**
 944      * An InputStream that delegates read/available operations to an underlying
 945      * input stream. The close method is overridden to close the Socket.
 946      *
 947      * This class is instrumented by Java Flight Recorder (JFR) to get socket
 948      * I/O events.
 949      */
 950     private static class SocketInputStream extends InputStream {
 951         private final Socket parent;
 952         private final InputStream in;
 953 
 954         SocketInputStream(Socket parent, InputStream in) {
 955             this.parent = parent;
 956             this.in = in;
 957         }
 958         @Override
 959         public int read() throws IOException {
 960             byte[] a = new byte[1];
 961             int n = read(a, 0, 1);
 962             return (n > 0) ? (a[0] & 0xff) : -1;
 963         }
 964         @Override
 965         public int read(byte[] b, int off, int len) throws IOException {
 966             return in.read(b, off, len);











 967         }
 968         @Override
 969         public int available() throws IOException {
 970             return in.available();
 971         }
 972 
 973         @Override
 974         public void close() throws IOException {
 975             parent.close();
 976         }
 977     }
 978 
 979     /**
 980      * Returns an output stream for this socket.
 981      *
 982      * <p> If this socket has an associated channel then the resulting output
 983      * stream delegates all of its operations to the channel.  If the channel
 984      * is in non-blocking mode then the output stream's {@code write}
 985      * operations will throw an {@link
 986      * java.nio.channels.IllegalBlockingModeException}.
 987      *





 988      * <p> Closing the returned {@link java.io.OutputStream OutputStream}
 989      * will close the associated socket.
 990      *
 991      * @return     an output stream for writing bytes to this socket.
 992      * @throws     IOException  if an I/O error occurs when creating the
 993      *               output stream or if the socket is not connected.
 994      * @revised 1.4
 995      */
 996     public OutputStream getOutputStream() throws IOException {
 997         if (isClosed())
 998             throw new SocketException("Socket is closed");
 999         if (!isConnected())
1000             throw new SocketException("Socket is not connected");
1001         if (isOutputShutdown())
1002             throw new SocketException("Socket output is shutdown");
1003         OutputStream out = this.out;
1004         if (out == null) {
1005             // wrap the output stream so that the close method closes this socket
1006             out = new SocketOutputStream(this, impl.getOutputStream());
1007             if (!OUT.compareAndSet(this, null, out)) {

1015      * An OutputStream that delegates write operations to an underlying output
1016      * stream. The close method is overridden to close the Socket.
1017      *
1018      * This class is instrumented by Java Flight Recorder (JFR) to get socket
1019      * I/O events.
1020      */
1021     private static class SocketOutputStream extends OutputStream {
1022         private final Socket parent;
1023         private final OutputStream out;
1024         SocketOutputStream(Socket parent, OutputStream out) {
1025             this.parent = parent;
1026             this.out = out;
1027         }
1028         @Override
1029         public void write(int b) throws IOException {
1030             byte[] a = new byte[] { (byte) b };
1031             write(a, 0, 1);
1032         }
1033         @Override
1034         public void write(byte[] b, int off, int len) throws IOException {
1035             out.write(b, off, len);









1036         }
1037 
1038         @Override
1039         public void close() throws IOException {
1040             parent.close();
1041         }
1042     }
1043 
1044     /**
1045      * Enable/disable {@link SocketOptions#TCP_NODELAY TCP_NODELAY}
1046      * (disable/enable Nagle's algorithm).
1047      *
1048      * @param on {@code true} to enable TCP_NODELAY,
1049      * {@code false} to disable.
1050      *
1051      * @throws    SocketException if there is an error
1052      * in the underlying protocol, such as a TCP error.
1053      *
1054      * @since   1.1
1055      *
1056      * @see #getTcpNoDelay()
1057      */

  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.net;
  27 
  28 import sun.security.util.SecurityConstants;
  29 
  30 import java.io.InputStream;
  31 import java.io.InterruptedIOException;
  32 import java.io.OutputStream;
  33 import java.io.IOException;
  34 import java.lang.invoke.MethodHandles;
  35 import java.lang.invoke.VarHandle;
  36 import java.nio.channels.SocketChannel;
  37 import java.util.Objects;
  38 import java.util.Set;
  39 import java.util.Collections;
  40 
  41 /**
  42  * This class implements client sockets (also called just
  43  * "sockets"). A socket is an endpoint for communication
  44  * between two machines.
  45  * <p>
  46  * The actual work of the socket is performed by an instance of the
  47  * {@code SocketImpl} class.
  48  *
  49  * <p> The {@code Socket} class defines convenience
  50  * methods to set and get several socket options. This class also
  51  * defines the {@link #setOption(SocketOption, Object) setOption}

 554         }
 555     }
 556 
 557     /**
 558      * Get the {@code SocketImpl} attached to this socket, creating
 559      * it if necessary.
 560      *
 561      * @return  the {@code SocketImpl} attached to that ServerSocket.
 562      * @throws SocketException if creation fails
 563      * @since 1.4
 564      */
 565     SocketImpl getImpl() throws SocketException {
 566         if (!created)
 567             createImpl(true);
 568         return impl;
 569     }
 570 
 571     /**
 572      * Connects this socket to the server.
 573      *
 574      * <p> For the system-default socket implementation at least, if a
 575      * {@linkplain Thread#isVirtual() virtual thread} blocked in {@code connect}
 576      * is {@linkplain Thread#interrupt() interrupted} then the socket is closed
 577      * and {@link SocketException} is thrown with the interrupt status set.
 578      *
 579      * @param   endpoint the {@code SocketAddress}
 580      * @throws  IOException if an error occurs during the connection
 581      * @throws  java.nio.channels.IllegalBlockingModeException
 582      *          if this socket has an associated channel,
 583      *          and the channel is in non-blocking mode
 584      * @throws  IllegalArgumentException if endpoint is null or is a
 585      *          SocketAddress subclass not supported by this socket
 586      * @since 1.4
 587      */
 588     public void connect(SocketAddress endpoint) throws IOException {
 589         connect(endpoint, 0);
 590     }
 591 
 592     /**
 593      * Connects this socket to the server with a specified timeout value.
 594      * A timeout of zero is interpreted as an infinite timeout. The connection
 595      * will then block until established or an error occurs.
 596      *
 597      * <p> For the system-default socket implementation at least, if a
 598      * {@linkplain Thread#isVirtual() virtual thread} blocked in {@code connect}
 599      * is {@linkplain Thread#interrupt() interrupted} then the socket is closed
 600      * and {@link SocketException} is thrown with the interrupt status set.
 601      *
 602      * @param   endpoint the {@code SocketAddress}
 603      * @param   timeout  the timeout value to be used in milliseconds.
 604      * @throws  IOException if an error occurs during the connection
 605      * @throws  SocketTimeoutException if timeout expires before connecting
 606      * @throws  java.nio.channels.IllegalBlockingModeException
 607      *          if this socket has an associated channel,
 608      *          and the channel is in non-blocking mode
 609      * @throws  IllegalArgumentException if endpoint is null or is a
 610      *          SocketAddress subclass not supported by this socket, or
 611      *          if {@code timeout} is negative
 612      * @since 1.4
 613      */
 614     public void connect(SocketAddress endpoint, int timeout) throws IOException {
 615         if (endpoint == null)
 616             throw new IllegalArgumentException("connect: The address can't be null");
 617 
 618         if (timeout < 0)
 619           throw new IllegalArgumentException("connect: timeout can't be negative");
 620 
 621         if (isClosed())

 624         if (isConnected())
 625             throw new SocketException("already connected");
 626 
 627         if (!(endpoint instanceof InetSocketAddress epoint))
 628             throw new IllegalArgumentException("Unsupported address type");
 629 
 630         InetAddress addr = epoint.getAddress ();
 631         int port = epoint.getPort();
 632         checkAddress(addr, "connect");
 633 
 634         @SuppressWarnings("removal")
 635         SecurityManager security = System.getSecurityManager();
 636         if (security != null) {
 637             if (epoint.isUnresolved())
 638                 security.checkConnect(epoint.getHostName(), port);
 639             else
 640                 security.checkConnect(addr.getHostAddress(), port);
 641         }
 642         if (!created)
 643             createImpl(true);
 644         try {
 645             impl.connect(epoint, timeout);
 646         } catch (SocketTimeoutException e) {
 647             throw e;
 648         } catch (InterruptedIOException e) {
 649             Thread thread = Thread.currentThread();
 650             if (thread.isVirtual() && thread.isInterrupted()) {
 651                 close();
 652                 throw new SocketException("Closed by interrupt");
 653             }
 654             throw e;
 655         }
 656         connected = true;
 657         /*
 658          * If the socket was not bound before the connect, it is now because
 659          * the kernel will have picked an ephemeral port & a local address
 660          */
 661         bound = true;
 662     }
 663 
 664     /**
 665      * Binds the socket to a local address.
 666      * <P>
 667      * If the address is {@code null}, then the system will pick up
 668      * an ephemeral port and a valid local address to bind the socket.
 669      *
 670      * @param   bindpoint the {@code SocketAddress} to bind to
 671      * @throws  IOException if the bind operation fails, or if the socket
 672      *                     is already bound.
 673      * @throws  IllegalArgumentException if bindpoint is a
 674      *          SocketAddress subclass not supported by this socket
 675      * @throws  SecurityException  if a security manager exists and its

 916      *
 917      * <ul>
 918      *
 919      *   <li><p>The network software may discard bytes that are buffered
 920      *   by the socket. Bytes that aren't discarded by the network
 921      *   software can be read using {@link java.io.InputStream#read read}.
 922      *
 923      *   <li><p>If there are no bytes buffered on the socket, or all
 924      *   buffered bytes have been consumed by
 925      *   {@link java.io.InputStream#read read}, then all subsequent
 926      *   calls to {@link java.io.InputStream#read read} will throw an
 927      *   {@link java.io.IOException IOException}.
 928      *
 929      *   <li><p>If there are no bytes buffered on the socket, and the
 930      *   socket has not been closed using {@link #close close}, then
 931      *   {@link java.io.InputStream#available available} will
 932      *   return {@code 0}.
 933      *
 934      * </ul>
 935      *
 936      * <p> For the system-default socket implementation at least, if a
 937      * {@linkplain Thread#isVirtual() virtual thread} blocked in {@code read}
 938      * is {@linkplain Thread#interrupt() interrupted} then the socket is closed
 939      * and {@link SocketException} is thrown with the interrupt status set.
 940      *
 941      * <p> Closing the returned {@link java.io.InputStream InputStream}
 942      * will close the associated socket.
 943      *
 944      * @return     an input stream for reading bytes from this socket.
 945      * @throws     IOException  if an I/O error occurs when creating the
 946      *             input stream, the socket is closed, the socket is
 947      *             not connected, or the socket input has been shutdown
 948      *             using {@link #shutdownInput()}
 949      *
 950      * @revised 1.4
 951      */
 952     public InputStream getInputStream() throws IOException {
 953         if (isClosed())
 954             throw new SocketException("Socket is closed");
 955         if (!isConnected())
 956             throw new SocketException("Socket is not connected");
 957         if (isInputShutdown())
 958             throw new SocketException("Socket input is shutdown");
 959         InputStream in = this.in;
 960         if (in == null) {
 961             // wrap the input stream so that the close method closes this socket
 962             in = new SocketInputStream(this, impl.getInputStream());
 963             if (!IN.compareAndSet(this, null, in)) {
 964                 in = this.in;
 965             }
 966         }
 967         return in;
 968     }
 969 
 970     /**
 971      * An InputStream that delegates read/available operations to an underlying
 972      * input stream. The close method is overridden to close the Socket.
 973      *
 974      * This class is instrumented by Java Flight Recorder (JFR) to get socket
 975      * I/O events.
 976      */
 977     private static class SocketInputStream extends InputStream {
 978         private final Socket parent;
 979         private final InputStream in;

 980         SocketInputStream(Socket parent, InputStream in) {
 981             this.parent = parent;
 982             this.in = in;
 983         }
 984         @Override
 985         public int read() throws IOException {
 986             byte[] a = new byte[1];
 987             int n = read(a, 0, 1);
 988             return (n > 0) ? (a[0] & 0xff) : -1;
 989         }
 990         @Override
 991         public int read(byte[] b, int off, int len) throws IOException {
 992             try {
 993                 return in.read(b, off, len);
 994             } catch (SocketTimeoutException e) {
 995                 throw e;
 996             } catch (InterruptedIOException e) {
 997                 Thread thread = Thread.currentThread();
 998                 if (thread.isVirtual() && thread.isInterrupted()) {
 999                     close();
1000                     throw new SocketException("Closed by interrupt");
1001                 }
1002                 throw e;
1003             }
1004         }
1005         @Override
1006         public int available() throws IOException {
1007             return in.available();
1008         }

1009         @Override
1010         public void close() throws IOException {
1011             parent.close();
1012         }
1013     }
1014 
1015     /**
1016      * Returns an output stream for this socket.
1017      *
1018      * <p> If this socket has an associated channel then the resulting output
1019      * stream delegates all of its operations to the channel.  If the channel
1020      * is in non-blocking mode then the output stream's {@code write}
1021      * operations will throw an {@link
1022      * java.nio.channels.IllegalBlockingModeException}.
1023      *
1024      * <p> For the system-default socket implementation at least, if a
1025      * {@linkplain Thread#isVirtual() virtual thread} blocked in {@code write}
1026      * is {@linkplain Thread#interrupt() interrupted} then the socket is closed
1027      * and {@link SocketException} is thrown with the interrupt status set.
1028      *
1029      * <p> Closing the returned {@link java.io.OutputStream OutputStream}
1030      * will close the associated socket.
1031      *
1032      * @return     an output stream for writing bytes to this socket.
1033      * @throws     IOException  if an I/O error occurs when creating the
1034      *               output stream or if the socket is not connected.
1035      * @revised 1.4
1036      */
1037     public OutputStream getOutputStream() throws IOException {
1038         if (isClosed())
1039             throw new SocketException("Socket is closed");
1040         if (!isConnected())
1041             throw new SocketException("Socket is not connected");
1042         if (isOutputShutdown())
1043             throw new SocketException("Socket output is shutdown");
1044         OutputStream out = this.out;
1045         if (out == null) {
1046             // wrap the output stream so that the close method closes this socket
1047             out = new SocketOutputStream(this, impl.getOutputStream());
1048             if (!OUT.compareAndSet(this, null, out)) {

1056      * An OutputStream that delegates write operations to an underlying output
1057      * stream. The close method is overridden to close the Socket.
1058      *
1059      * This class is instrumented by Java Flight Recorder (JFR) to get socket
1060      * I/O events.
1061      */
1062     private static class SocketOutputStream extends OutputStream {
1063         private final Socket parent;
1064         private final OutputStream out;
1065         SocketOutputStream(Socket parent, OutputStream out) {
1066             this.parent = parent;
1067             this.out = out;
1068         }
1069         @Override
1070         public void write(int b) throws IOException {
1071             byte[] a = new byte[] { (byte) b };
1072             write(a, 0, 1);
1073         }
1074         @Override
1075         public void write(byte[] b, int off, int len) throws IOException {
1076             try {
1077                 out.write(b, off, len);
1078             } catch (InterruptedIOException e) {
1079                 Thread thread = Thread.currentThread();
1080                 if (thread.isVirtual() && thread.isInterrupted()) {
1081                     close();
1082                     throw new SocketException("Closed by interrupt");
1083                 }
1084                 throw e;
1085             }
1086         }

1087         @Override
1088         public void close() throws IOException {
1089             parent.close();
1090         }
1091     }
1092 
1093     /**
1094      * Enable/disable {@link SocketOptions#TCP_NODELAY TCP_NODELAY}
1095      * (disable/enable Nagle's algorithm).
1096      *
1097      * @param on {@code true} to enable TCP_NODELAY,
1098      * {@code false} to disable.
1099      *
1100      * @throws    SocketException if there is an error
1101      * in the underlying protocol, such as a TCP error.
1102      *
1103      * @since   1.1
1104      *
1105      * @see #getTcpNoDelay()
1106      */
< prev index next >