< prev index next >

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

Print this page
rev 56290 : 8230648: Replace @exception tag with @throws in java.base
Summary: Minor coding style update of javadoc tag in any file in java.base
Reviewed-by: prappo, lancea


  66      */
  67     private SocketImpl impl;
  68 
  69     /**
  70      * Creates a server socket with a user-specified {@code SocketImpl}.
  71      *
  72      * @param      impl an instance of a SocketImpl to use on the ServerSocket.
  73      *
  74      * @throws     NullPointerException if impl is {@code null}.
  75      *
  76      * @since 12
  77      */
  78     protected ServerSocket(SocketImpl impl) {
  79         Objects.requireNonNull(impl);
  80         this.impl = impl;
  81     }
  82 
  83     /**
  84      * Creates an unbound server socket.
  85      *
  86      * @exception IOException IO error when opening the socket.
  87      * @revised 1.4
  88      */
  89     public ServerSocket() throws IOException {
  90         setImpl();
  91     }
  92 
  93     /**
  94      * Creates a server socket, bound to the specified port. A port number
  95      * of {@code 0} means that the port number is automatically
  96      * allocated, typically from an ephemeral port range. This port
  97      * number can then be retrieved by calling {@link #getLocalPort getLocalPort}.
  98      * <p>
  99      * The maximum queue length for incoming connection indications (a
 100      * request to connect) is set to {@code 50}. If a connection
 101      * indication arrives when the queue is full, the connection is refused.
 102      * <p>
 103      * If the application has specified a server socket implementation
 104      * factory, that factory's {@code createSocketImpl} method is called to
 105      * create the actual socket implementation. Otherwise a system-default
 106      * socket implementation is created.
 107      * <p>
 108      * If there is a security manager,
 109      * its {@code checkListen} method is called
 110      * with the {@code port} argument
 111      * as its argument to ensure the operation is allowed.
 112      * This could result in a SecurityException.
 113      *
 114      *
 115      * @param      port  the port number, or {@code 0} to use a port
 116      *                   number that is automatically allocated.
 117      *
 118      * @exception  IOException  if an I/O error occurs when opening the socket.
 119      * @exception  SecurityException
 120      * if a security manager exists and its {@code checkListen}
 121      * method doesn't allow the operation.
 122      * @exception  IllegalArgumentException if the port parameter is outside
 123      *             the specified range of valid port values, which is between
 124      *             0 and 65535, inclusive.
 125      *
 126      * @see        java.net.SocketImpl
 127      * @see        java.net.SocketImplFactory#createSocketImpl()
 128      * @see        java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory)
 129      * @see        SecurityManager#checkListen
 130      */
 131     public ServerSocket(int port) throws IOException {
 132         this(port, 50, null);
 133     }
 134 
 135     /**
 136      * Creates a server socket and binds it to the specified local port
 137      * number, with the specified backlog.
 138      * A port number of {@code 0} means that the port number is
 139      * automatically allocated, typically from an ephemeral port range.
 140      * This port number can then be retrieved by calling
 141      * {@link #getLocalPort getLocalPort}.
 142      * <p>


 151      * socket implementation is created.
 152      * <p>
 153      * If there is a security manager,
 154      * its {@code checkListen} method is called
 155      * with the {@code port} argument
 156      * as its argument to ensure the operation is allowed.
 157      * This could result in a SecurityException.
 158      *
 159      * The {@code backlog} argument is the requested maximum number of
 160      * pending connections on the socket. Its exact semantics are implementation
 161      * specific. In particular, an implementation may impose a maximum length
 162      * or may choose to ignore the parameter altogether. The value provided
 163      * should be greater than {@code 0}. If it is less than or equal to
 164      * {@code 0}, then an implementation specific default will be used.
 165      *
 166      * @param      port     the port number, or {@code 0} to use a port
 167      *                      number that is automatically allocated.
 168      * @param      backlog  requested maximum length of the queue of incoming
 169      *                      connections.
 170      *
 171      * @exception  IOException  if an I/O error occurs when opening the socket.
 172      * @exception  SecurityException
 173      * if a security manager exists and its {@code checkListen}
 174      * method doesn't allow the operation.
 175      * @exception  IllegalArgumentException if the port parameter is outside
 176      *             the specified range of valid port values, which is between
 177      *             0 and 65535, inclusive.
 178      *
 179      * @see        java.net.SocketImpl
 180      * @see        java.net.SocketImplFactory#createSocketImpl()
 181      * @see        java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory)
 182      * @see        SecurityManager#checkListen
 183      */
 184     public ServerSocket(int port, int backlog) throws IOException {
 185         this(port, backlog, null);
 186     }
 187 
 188     /**
 189      * Create a server with the specified port, listen backlog, and
 190      * local IP address to bind to.  The <i>bindAddr</i> argument
 191      * can be used on a multi-homed host for a ServerSocket that
 192      * will only accept connect requests to one of its addresses.
 193      * If <i>bindAddr</i> is null, it will default accepting
 194      * connections on any/all local addresses.
 195      * The port must be between 0 and 65535, inclusive.


 204      * as its argument to ensure the operation is allowed.
 205      * This could result in a SecurityException.
 206      *
 207      * The {@code backlog} argument is the requested maximum number of
 208      * pending connections on the socket. Its exact semantics are implementation
 209      * specific. In particular, an implementation may impose a maximum length
 210      * or may choose to ignore the parameter altogether. The value provided
 211      * should be greater than {@code 0}. If it is less than or equal to
 212      * {@code 0}, then an implementation specific default will be used.
 213      *
 214      * @param port  the port number, or {@code 0} to use a port
 215      *              number that is automatically allocated.
 216      * @param backlog requested maximum length of the queue of incoming
 217      *                connections.
 218      * @param bindAddr the local InetAddress the server will bind to
 219      *
 220      * @throws  SecurityException if a security manager exists and
 221      * its {@code checkListen} method doesn't allow the operation.
 222      *
 223      * @throws  IOException if an I/O error occurs when opening the socket.
 224      * @exception  IllegalArgumentException if the port parameter is outside
 225      *             the specified range of valid port values, which is between
 226      *             0 and 65535, inclusive.
 227      *
 228      * @see SocketOptions
 229      * @see SocketImpl
 230      * @see SecurityManager#checkListen
 231      * @since   1.1
 232      */
 233     public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException {
 234         setImpl();
 235         if (port < 0 || port > 0xFFFF)
 236             throw new IllegalArgumentException(
 237                        "Port value out of range: " + port);
 238         if (backlog < 1)
 239           backlog = 50;
 240         try {
 241             bind(new InetSocketAddress(bindAddr, port), backlog);
 242         } catch(SecurityException e) {
 243             close();
 244             throw e;


 457     }
 458 
 459     /**
 460      * Listens for a connection to be made to this socket and accepts
 461      * it. The method blocks until a connection is made.
 462      *
 463      * <p>A new Socket {@code s} is created and, if there
 464      * is a security manager,
 465      * the security manager's {@code checkAccept} method is called
 466      * with {@code s.getInetAddress().getHostAddress()} and
 467      * {@code s.getPort()}
 468      * as its arguments to ensure the operation is allowed.
 469      * This could result in a SecurityException.
 470      *
 471      * @implNote
 472      * An instance of this class using a system-default {@code SocketImpl}
 473      * accepts sockets with a {@code SocketImpl} of the same type, regardless
 474      * of the {@linkplain Socket#setSocketImplFactory(SocketImplFactory)
 475      * client socket implementation factory}, if one has been set.
 476      *
 477      * @exception  IOException  if an I/O error occurs when waiting for a
 478      *               connection.
 479      * @exception  SecurityException  if a security manager exists and its
 480      *             {@code checkAccept} method doesn't allow the operation.
 481      * @exception  SocketTimeoutException if a timeout was previously set with setSoTimeout and
 482      *             the timeout has been reached.
 483      * @exception  java.nio.channels.IllegalBlockingModeException
 484      *             if this socket has an associated channel, the channel is in
 485      *             non-blocking mode, and there is no connection ready to be
 486      *             accepted
 487      *
 488      * @return the new Socket
 489      * @see SecurityManager#checkAccept
 490      * @revised 1.4
 491      * @spec JSR-51
 492      */
 493     public Socket accept() throws IOException {
 494         if (isClosed())
 495             throw new SocketException("Socket is closed");
 496         if (!isBound())
 497             throw new SocketException("Socket is not bound yet");
 498         Socket s = new Socket((SocketImpl) null);
 499         implAccept(s);
 500         return s;
 501     }
 502 
 503     /**


 657     /**
 658      * Throws IOException if the server SocketImpl and the given client
 659      * SocketImpl are not both platform or custom SocketImpls.
 660      */
 661     private void ensureCompatible(SocketImpl si) throws IOException {
 662         if ((impl instanceof PlatformSocketImpl) != (si instanceof PlatformSocketImpl)) {
 663             throw new IOException("An instance of " + impl.getClass() +
 664                 " cannot accept a connection with an instance of " + si.getClass());
 665         }
 666     }
 667 
 668     /**
 669      * Closes this socket.
 670      *
 671      * Any thread currently blocked in {@link #accept()} will throw
 672      * a {@link SocketException}.
 673      *
 674      * <p> If this socket has an associated channel then the channel is closed
 675      * as well.
 676      *
 677      * @exception  IOException  if an I/O error occurs when closing the socket.
 678      * @revised 1.4
 679      * @spec JSR-51
 680      */
 681     public void close() throws IOException {
 682         synchronized(closeLock) {
 683             if (isClosed())
 684                 return;
 685             if (created)
 686                 impl.close();
 687             closed = true;
 688         }
 689     }
 690 
 691     /**
 692      * Returns the unique {@link java.nio.channels.ServerSocketChannel} object
 693      * associated with this socket, if any.
 694      *
 695      * <p> A server socket will have a channel if, and only if, the channel
 696      * itself was created via the {@link
 697      * java.nio.channels.ServerSocketChannel#open ServerSocketChannel.open}


 746      * A timeout of zero is interpreted as an infinite timeout.
 747      * @param timeout the specified timeout, in milliseconds
 748      * @throws  SocketException if there is an error in the underlying protocol,
 749      *          such as a TCP error
 750      * @throws  IllegalArgumentException  if {@code timeout} is negative
 751      * @since   1.1
 752      * @see #getSoTimeout()
 753      */
 754     public synchronized void setSoTimeout(int timeout) throws SocketException {
 755         if (isClosed())
 756             throw new SocketException("Socket is closed");
 757         if (timeout < 0)
 758             throw new IllegalArgumentException("timeout < 0");
 759         getImpl().setOption(SocketOptions.SO_TIMEOUT, timeout);
 760     }
 761 
 762     /**
 763      * Retrieve setting for {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT}.
 764      * 0 returns implies that the option is disabled (i.e., timeout of infinity).
 765      * @return the {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT} value
 766      * @exception IOException if an I/O error occurs
 767      * @since   1.1
 768      * @see #setSoTimeout(int)
 769      */
 770     public synchronized int getSoTimeout() throws IOException {
 771         if (isClosed())
 772             throw new SocketException("Socket is closed");
 773         Object o = getImpl().getOption(SocketOptions.SO_TIMEOUT);
 774         /* extra type safety */
 775         if (o instanceof Integer) {
 776             return ((Integer) o).intValue();
 777         } else {
 778             return 0;
 779         }
 780     }
 781 
 782     /**
 783      * Enable/disable the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}
 784      * socket option.
 785      * <p>
 786      * When a TCP connection is closed the connection may remain


 789      * or {@code 2MSL} wait state).
 790      * For applications using a well known socket address or port
 791      * it may not be possible to bind a socket to the required
 792      * {@code SocketAddress} if there is a connection in the
 793      * timeout state involving the socket address or port.
 794      * <p>
 795      * Enabling {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} prior to
 796      * binding the socket using {@link #bind(SocketAddress)} allows the socket
 797      * to be bound even though a previous connection is in a timeout state.
 798      * <p>
 799      * When a {@code ServerSocket} is created the initial setting
 800      * of {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is not defined.
 801      * Applications can use {@link #getReuseAddress()} to determine the initial
 802      * setting of {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}.
 803      * <p>
 804      * The behaviour when {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is
 805      * enabled or disabled after a socket is bound (See {@link #isBound()})
 806      * is not defined.
 807      *
 808      * @param on  whether to enable or disable the socket option
 809      * @exception SocketException if an error occurs enabling or
 810      *            disabling the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}
 811      *            socket option, or the socket is closed.
 812      * @since 1.4
 813      * @see #getReuseAddress()
 814      * @see #bind(SocketAddress)
 815      * @see #isBound()
 816      * @see #isClosed()
 817      */
 818     public void setReuseAddress(boolean on) throws SocketException {
 819         if (isClosed())
 820             throw new SocketException("Socket is closed");
 821         getImpl().setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(on));
 822     }
 823 
 824     /**
 825      * Tests if {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled.
 826      *
 827      * @return a {@code boolean} indicating whether or not
 828      *         {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled.
 829      * @exception SocketException if there is an error
 830      * in the underlying protocol, such as a TCP error.
 831      * @since   1.4
 832      * @see #setReuseAddress(boolean)
 833      */
 834     public boolean getReuseAddress() throws SocketException {
 835         if (isClosed())
 836             throw new SocketException("Socket is closed");
 837         return ((Boolean) (getImpl().getOption(SocketOptions.SO_REUSEADDR))).booleanValue();
 838     }
 839 
 840     /**
 841      * Returns the implementation address and implementation port of
 842      * this socket as a {@code String}.
 843      * <p>
 844      * If there is a security manager set, and this socket is
 845      * {@linkplain #isBound bound}, its {@code checkConnect} method is
 846      * called with the local address and {@code -1} as its arguments to see
 847      * if the operation is allowed. If the operation is not allowed,
 848      * an {@code InetAddress} representing the
 849      * {@link InetAddress#getLoopbackAddress loopback} address is returned as


 868      */
 869     private static volatile SocketImplFactory factory;
 870 
 871     /**
 872      * Sets the server socket implementation factory for the
 873      * application. The factory can be specified only once.
 874      * <p>
 875      * When an application creates a new server socket, the socket
 876      * implementation factory's {@code createSocketImpl} method is
 877      * called to create the actual socket implementation.
 878      * <p>
 879      * Passing {@code null} to the method is a no-op unless the factory
 880      * was already set.
 881      * <p>
 882      * If there is a security manager, this method first calls
 883      * the security manager's {@code checkSetFactory} method
 884      * to ensure the operation is allowed.
 885      * This could result in a SecurityException.
 886      *
 887      * @param      fac   the desired factory.
 888      * @exception  IOException  if an I/O error occurs when setting the
 889      *               socket factory.
 890      * @exception  SocketException  if the factory has already been defined.
 891      * @exception  SecurityException  if a security manager exists and its
 892      *             {@code checkSetFactory} method doesn't allow the operation.
 893      * @see        java.net.SocketImplFactory#createSocketImpl()
 894      * @see        SecurityManager#checkSetFactory
 895      */
 896     public static synchronized void setSocketFactory(SocketImplFactory fac) throws IOException {
 897         if (factory != null) {
 898             throw new SocketException("factory already defined");
 899         }
 900         SecurityManager security = System.getSecurityManager();
 901         if (security != null) {
 902             security.checkSetFactory();
 903         }
 904         factory = fac;
 905     }
 906 
 907     /**
 908      * Sets a default proposed value for the
 909      * {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option for sockets
 910      * accepted from this {@code ServerSocket}. The value actually set
 911      * in the accepted socket must be determined by calling
 912      * {@link Socket#getReceiveBufferSize()} after the socket
 913      * is returned by {@link #accept()}.
 914      * <p>
 915      * The value of {@link SocketOptions#SO_RCVBUF SO_RCVBUF} is used both to
 916      * set the size of the internal socket receive buffer, and to set the size
 917      * of the TCP receive window that is advertised to the remote peer.
 918      * <p>
 919      * It is possible to change the value subsequently, by calling
 920      * {@link Socket#setReceiveBufferSize(int)}. However, if the application
 921      * wishes to allow a receive window larger than 64K bytes, as defined by RFC1323
 922      * then the proposed value must be set in the ServerSocket <B>before</B>
 923      * it is bound to a local address. This implies, that the ServerSocket must be
 924      * created with the no-argument constructor, then setReceiveBufferSize() must
 925      * be called and lastly the ServerSocket is bound to an address by calling bind().
 926      * <p>
 927      * Failure to do this will not cause an error, and the buffer size may be set to the
 928      * requested value but the TCP receive window in sockets accepted from
 929      * this ServerSocket will be no larger than 64K bytes.
 930      *
 931      * @exception SocketException if there is an error
 932      * in the underlying protocol, such as a TCP error.
 933      *
 934      * @param size the size to which to set the receive buffer
 935      * size. This value must be greater than 0.
 936      *
 937      * @exception IllegalArgumentException if the
 938      * value is 0 or is negative.
 939      *
 940      * @since 1.4
 941      * @see #getReceiveBufferSize
 942      */
 943      public synchronized void setReceiveBufferSize (int size) throws SocketException {
 944         if (!(size > 0)) {
 945             throw new IllegalArgumentException("negative receive size");
 946         }
 947         if (isClosed())
 948             throw new SocketException("Socket is closed");
 949         getImpl().setOption(SocketOptions.SO_RCVBUF, size);
 950     }
 951 
 952     /**
 953      * Gets the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option
 954      * for this {@code ServerSocket}, that is the proposed buffer size that
 955      * will be used for Sockets accepted from this {@code ServerSocket}.
 956      *
 957      * <p>Note, the value actually set in the accepted socket is determined by
 958      * calling {@link Socket#getReceiveBufferSize()}.
 959      * @return the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF}
 960      *         option for this {@code Socket}.
 961      * @exception SocketException if there is an error
 962      *            in the underlying protocol, such as a TCP error.
 963      * @see #setReceiveBufferSize(int)
 964      * @since 1.4
 965      */
 966     public synchronized int getReceiveBufferSize()
 967     throws SocketException{
 968         if (isClosed())
 969             throw new SocketException("Socket is closed");
 970         int result = 0;
 971         Object o = getImpl().getOption(SocketOptions.SO_RCVBUF);
 972         if (o instanceof Integer) {
 973             result = ((Integer)o).intValue();
 974         }
 975         return result;
 976     }
 977 
 978     /**
 979      * Sets performance preferences for this ServerSocket.
 980      *
 981      * <p> Sockets use the TCP/IP protocol by default.  Some implementations




  66      */
  67     private SocketImpl impl;
  68 
  69     /**
  70      * Creates a server socket with a user-specified {@code SocketImpl}.
  71      *
  72      * @param      impl an instance of a SocketImpl to use on the ServerSocket.
  73      *
  74      * @throws     NullPointerException if impl is {@code null}.
  75      *
  76      * @since 12
  77      */
  78     protected ServerSocket(SocketImpl impl) {
  79         Objects.requireNonNull(impl);
  80         this.impl = impl;
  81     }
  82 
  83     /**
  84      * Creates an unbound server socket.
  85      *
  86      * @throws    IOException IO error when opening the socket.
  87      * @revised 1.4
  88      */
  89     public ServerSocket() throws IOException {
  90         setImpl();
  91     }
  92 
  93     /**
  94      * Creates a server socket, bound to the specified port. A port number
  95      * of {@code 0} means that the port number is automatically
  96      * allocated, typically from an ephemeral port range. This port
  97      * number can then be retrieved by calling {@link #getLocalPort getLocalPort}.
  98      * <p>
  99      * The maximum queue length for incoming connection indications (a
 100      * request to connect) is set to {@code 50}. If a connection
 101      * indication arrives when the queue is full, the connection is refused.
 102      * <p>
 103      * If the application has specified a server socket implementation
 104      * factory, that factory's {@code createSocketImpl} method is called to
 105      * create the actual socket implementation. Otherwise a system-default
 106      * socket implementation is created.
 107      * <p>
 108      * If there is a security manager,
 109      * its {@code checkListen} method is called
 110      * with the {@code port} argument
 111      * as its argument to ensure the operation is allowed.
 112      * This could result in a SecurityException.
 113      *
 114      *
 115      * @param      port  the port number, or {@code 0} to use a port
 116      *                   number that is automatically allocated.
 117      *
 118      * @throws     IOException  if an I/O error occurs when opening the socket.
 119      * @throws     SecurityException
 120      * if a security manager exists and its {@code checkListen}
 121      * method doesn't allow the operation.
 122      * @throws     IllegalArgumentException if the port parameter is outside
 123      *             the specified range of valid port values, which is between
 124      *             0 and 65535, inclusive.
 125      *
 126      * @see        java.net.SocketImpl
 127      * @see        java.net.SocketImplFactory#createSocketImpl()
 128      * @see        java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory)
 129      * @see        SecurityManager#checkListen
 130      */
 131     public ServerSocket(int port) throws IOException {
 132         this(port, 50, null);
 133     }
 134 
 135     /**
 136      * Creates a server socket and binds it to the specified local port
 137      * number, with the specified backlog.
 138      * A port number of {@code 0} means that the port number is
 139      * automatically allocated, typically from an ephemeral port range.
 140      * This port number can then be retrieved by calling
 141      * {@link #getLocalPort getLocalPort}.
 142      * <p>


 151      * socket implementation is created.
 152      * <p>
 153      * If there is a security manager,
 154      * its {@code checkListen} method is called
 155      * with the {@code port} argument
 156      * as its argument to ensure the operation is allowed.
 157      * This could result in a SecurityException.
 158      *
 159      * The {@code backlog} argument is the requested maximum number of
 160      * pending connections on the socket. Its exact semantics are implementation
 161      * specific. In particular, an implementation may impose a maximum length
 162      * or may choose to ignore the parameter altogether. The value provided
 163      * should be greater than {@code 0}. If it is less than or equal to
 164      * {@code 0}, then an implementation specific default will be used.
 165      *
 166      * @param      port     the port number, or {@code 0} to use a port
 167      *                      number that is automatically allocated.
 168      * @param      backlog  requested maximum length of the queue of incoming
 169      *                      connections.
 170      *
 171      * @throws     IOException  if an I/O error occurs when opening the socket.
 172      * @throws     SecurityException
 173      * if a security manager exists and its {@code checkListen}
 174      * method doesn't allow the operation.
 175      * @throws     IllegalArgumentException if the port parameter is outside
 176      *             the specified range of valid port values, which is between
 177      *             0 and 65535, inclusive.
 178      *
 179      * @see        java.net.SocketImpl
 180      * @see        java.net.SocketImplFactory#createSocketImpl()
 181      * @see        java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory)
 182      * @see        SecurityManager#checkListen
 183      */
 184     public ServerSocket(int port, int backlog) throws IOException {
 185         this(port, backlog, null);
 186     }
 187 
 188     /**
 189      * Create a server with the specified port, listen backlog, and
 190      * local IP address to bind to.  The <i>bindAddr</i> argument
 191      * can be used on a multi-homed host for a ServerSocket that
 192      * will only accept connect requests to one of its addresses.
 193      * If <i>bindAddr</i> is null, it will default accepting
 194      * connections on any/all local addresses.
 195      * The port must be between 0 and 65535, inclusive.


 204      * as its argument to ensure the operation is allowed.
 205      * This could result in a SecurityException.
 206      *
 207      * The {@code backlog} argument is the requested maximum number of
 208      * pending connections on the socket. Its exact semantics are implementation
 209      * specific. In particular, an implementation may impose a maximum length
 210      * or may choose to ignore the parameter altogether. The value provided
 211      * should be greater than {@code 0}. If it is less than or equal to
 212      * {@code 0}, then an implementation specific default will be used.
 213      *
 214      * @param port  the port number, or {@code 0} to use a port
 215      *              number that is automatically allocated.
 216      * @param backlog requested maximum length of the queue of incoming
 217      *                connections.
 218      * @param bindAddr the local InetAddress the server will bind to
 219      *
 220      * @throws  SecurityException if a security manager exists and
 221      * its {@code checkListen} method doesn't allow the operation.
 222      *
 223      * @throws  IOException if an I/O error occurs when opening the socket.
 224      * @throws     IllegalArgumentException if the port parameter is outside
 225      *             the specified range of valid port values, which is between
 226      *             0 and 65535, inclusive.
 227      *
 228      * @see SocketOptions
 229      * @see SocketImpl
 230      * @see SecurityManager#checkListen
 231      * @since   1.1
 232      */
 233     public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException {
 234         setImpl();
 235         if (port < 0 || port > 0xFFFF)
 236             throw new IllegalArgumentException(
 237                        "Port value out of range: " + port);
 238         if (backlog < 1)
 239           backlog = 50;
 240         try {
 241             bind(new InetSocketAddress(bindAddr, port), backlog);
 242         } catch(SecurityException e) {
 243             close();
 244             throw e;


 457     }
 458 
 459     /**
 460      * Listens for a connection to be made to this socket and accepts
 461      * it. The method blocks until a connection is made.
 462      *
 463      * <p>A new Socket {@code s} is created and, if there
 464      * is a security manager,
 465      * the security manager's {@code checkAccept} method is called
 466      * with {@code s.getInetAddress().getHostAddress()} and
 467      * {@code s.getPort()}
 468      * as its arguments to ensure the operation is allowed.
 469      * This could result in a SecurityException.
 470      *
 471      * @implNote
 472      * An instance of this class using a system-default {@code SocketImpl}
 473      * accepts sockets with a {@code SocketImpl} of the same type, regardless
 474      * of the {@linkplain Socket#setSocketImplFactory(SocketImplFactory)
 475      * client socket implementation factory}, if one has been set.
 476      *
 477      * @throws     IOException  if an I/O error occurs when waiting for a
 478      *               connection.
 479      * @throws     SecurityException  if a security manager exists and its
 480      *             {@code checkAccept} method doesn't allow the operation.
 481      * @throws     SocketTimeoutException if a timeout was previously set with setSoTimeout and
 482      *             the timeout has been reached.
 483      * @throws     java.nio.channels.IllegalBlockingModeException
 484      *             if this socket has an associated channel, the channel is in
 485      *             non-blocking mode, and there is no connection ready to be
 486      *             accepted
 487      *
 488      * @return the new Socket
 489      * @see SecurityManager#checkAccept
 490      * @revised 1.4
 491      * @spec JSR-51
 492      */
 493     public Socket accept() throws IOException {
 494         if (isClosed())
 495             throw new SocketException("Socket is closed");
 496         if (!isBound())
 497             throw new SocketException("Socket is not bound yet");
 498         Socket s = new Socket((SocketImpl) null);
 499         implAccept(s);
 500         return s;
 501     }
 502 
 503     /**


 657     /**
 658      * Throws IOException if the server SocketImpl and the given client
 659      * SocketImpl are not both platform or custom SocketImpls.
 660      */
 661     private void ensureCompatible(SocketImpl si) throws IOException {
 662         if ((impl instanceof PlatformSocketImpl) != (si instanceof PlatformSocketImpl)) {
 663             throw new IOException("An instance of " + impl.getClass() +
 664                 " cannot accept a connection with an instance of " + si.getClass());
 665         }
 666     }
 667 
 668     /**
 669      * Closes this socket.
 670      *
 671      * Any thread currently blocked in {@link #accept()} will throw
 672      * a {@link SocketException}.
 673      *
 674      * <p> If this socket has an associated channel then the channel is closed
 675      * as well.
 676      *
 677      * @throws     IOException  if an I/O error occurs when closing the socket.
 678      * @revised 1.4
 679      * @spec JSR-51
 680      */
 681     public void close() throws IOException {
 682         synchronized(closeLock) {
 683             if (isClosed())
 684                 return;
 685             if (created)
 686                 impl.close();
 687             closed = true;
 688         }
 689     }
 690 
 691     /**
 692      * Returns the unique {@link java.nio.channels.ServerSocketChannel} object
 693      * associated with this socket, if any.
 694      *
 695      * <p> A server socket will have a channel if, and only if, the channel
 696      * itself was created via the {@link
 697      * java.nio.channels.ServerSocketChannel#open ServerSocketChannel.open}


 746      * A timeout of zero is interpreted as an infinite timeout.
 747      * @param timeout the specified timeout, in milliseconds
 748      * @throws  SocketException if there is an error in the underlying protocol,
 749      *          such as a TCP error
 750      * @throws  IllegalArgumentException  if {@code timeout} is negative
 751      * @since   1.1
 752      * @see #getSoTimeout()
 753      */
 754     public synchronized void setSoTimeout(int timeout) throws SocketException {
 755         if (isClosed())
 756             throw new SocketException("Socket is closed");
 757         if (timeout < 0)
 758             throw new IllegalArgumentException("timeout < 0");
 759         getImpl().setOption(SocketOptions.SO_TIMEOUT, timeout);
 760     }
 761 
 762     /**
 763      * Retrieve setting for {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT}.
 764      * 0 returns implies that the option is disabled (i.e., timeout of infinity).
 765      * @return the {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT} value
 766      * @throws    IOException if an I/O error occurs
 767      * @since   1.1
 768      * @see #setSoTimeout(int)
 769      */
 770     public synchronized int getSoTimeout() throws IOException {
 771         if (isClosed())
 772             throw new SocketException("Socket is closed");
 773         Object o = getImpl().getOption(SocketOptions.SO_TIMEOUT);
 774         /* extra type safety */
 775         if (o instanceof Integer) {
 776             return ((Integer) o).intValue();
 777         } else {
 778             return 0;
 779         }
 780     }
 781 
 782     /**
 783      * Enable/disable the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}
 784      * socket option.
 785      * <p>
 786      * When a TCP connection is closed the connection may remain


 789      * or {@code 2MSL} wait state).
 790      * For applications using a well known socket address or port
 791      * it may not be possible to bind a socket to the required
 792      * {@code SocketAddress} if there is a connection in the
 793      * timeout state involving the socket address or port.
 794      * <p>
 795      * Enabling {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} prior to
 796      * binding the socket using {@link #bind(SocketAddress)} allows the socket
 797      * to be bound even though a previous connection is in a timeout state.
 798      * <p>
 799      * When a {@code ServerSocket} is created the initial setting
 800      * of {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is not defined.
 801      * Applications can use {@link #getReuseAddress()} to determine the initial
 802      * setting of {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}.
 803      * <p>
 804      * The behaviour when {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is
 805      * enabled or disabled after a socket is bound (See {@link #isBound()})
 806      * is not defined.
 807      *
 808      * @param on  whether to enable or disable the socket option
 809      * @throws    SocketException if an error occurs enabling or
 810      *            disabling the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}
 811      *            socket option, or the socket is closed.
 812      * @since 1.4
 813      * @see #getReuseAddress()
 814      * @see #bind(SocketAddress)
 815      * @see #isBound()
 816      * @see #isClosed()
 817      */
 818     public void setReuseAddress(boolean on) throws SocketException {
 819         if (isClosed())
 820             throw new SocketException("Socket is closed");
 821         getImpl().setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(on));
 822     }
 823 
 824     /**
 825      * Tests if {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled.
 826      *
 827      * @return a {@code boolean} indicating whether or not
 828      *         {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled.
 829      * @throws    SocketException if there is an error
 830      * in the underlying protocol, such as a TCP error.
 831      * @since   1.4
 832      * @see #setReuseAddress(boolean)
 833      */
 834     public boolean getReuseAddress() throws SocketException {
 835         if (isClosed())
 836             throw new SocketException("Socket is closed");
 837         return ((Boolean) (getImpl().getOption(SocketOptions.SO_REUSEADDR))).booleanValue();
 838     }
 839 
 840     /**
 841      * Returns the implementation address and implementation port of
 842      * this socket as a {@code String}.
 843      * <p>
 844      * If there is a security manager set, and this socket is
 845      * {@linkplain #isBound bound}, its {@code checkConnect} method is
 846      * called with the local address and {@code -1} as its arguments to see
 847      * if the operation is allowed. If the operation is not allowed,
 848      * an {@code InetAddress} representing the
 849      * {@link InetAddress#getLoopbackAddress loopback} address is returned as


 868      */
 869     private static volatile SocketImplFactory factory;
 870 
 871     /**
 872      * Sets the server socket implementation factory for the
 873      * application. The factory can be specified only once.
 874      * <p>
 875      * When an application creates a new server socket, the socket
 876      * implementation factory's {@code createSocketImpl} method is
 877      * called to create the actual socket implementation.
 878      * <p>
 879      * Passing {@code null} to the method is a no-op unless the factory
 880      * was already set.
 881      * <p>
 882      * If there is a security manager, this method first calls
 883      * the security manager's {@code checkSetFactory} method
 884      * to ensure the operation is allowed.
 885      * This could result in a SecurityException.
 886      *
 887      * @param      fac   the desired factory.
 888      * @throws     IOException  if an I/O error occurs when setting the
 889      *               socket factory.
 890      * @throws     SocketException  if the factory has already been defined.
 891      * @throws     SecurityException  if a security manager exists and its
 892      *             {@code checkSetFactory} method doesn't allow the operation.
 893      * @see        java.net.SocketImplFactory#createSocketImpl()
 894      * @see        SecurityManager#checkSetFactory
 895      */
 896     public static synchronized void setSocketFactory(SocketImplFactory fac) throws IOException {
 897         if (factory != null) {
 898             throw new SocketException("factory already defined");
 899         }
 900         SecurityManager security = System.getSecurityManager();
 901         if (security != null) {
 902             security.checkSetFactory();
 903         }
 904         factory = fac;
 905     }
 906 
 907     /**
 908      * Sets a default proposed value for the
 909      * {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option for sockets
 910      * accepted from this {@code ServerSocket}. The value actually set
 911      * in the accepted socket must be determined by calling
 912      * {@link Socket#getReceiveBufferSize()} after the socket
 913      * is returned by {@link #accept()}.
 914      * <p>
 915      * The value of {@link SocketOptions#SO_RCVBUF SO_RCVBUF} is used both to
 916      * set the size of the internal socket receive buffer, and to set the size
 917      * of the TCP receive window that is advertised to the remote peer.
 918      * <p>
 919      * It is possible to change the value subsequently, by calling
 920      * {@link Socket#setReceiveBufferSize(int)}. However, if the application
 921      * wishes to allow a receive window larger than 64K bytes, as defined by RFC1323
 922      * then the proposed value must be set in the ServerSocket <B>before</B>
 923      * it is bound to a local address. This implies, that the ServerSocket must be
 924      * created with the no-argument constructor, then setReceiveBufferSize() must
 925      * be called and lastly the ServerSocket is bound to an address by calling bind().
 926      * <p>
 927      * Failure to do this will not cause an error, and the buffer size may be set to the
 928      * requested value but the TCP receive window in sockets accepted from
 929      * this ServerSocket will be no larger than 64K bytes.
 930      *
 931      * @throws    SocketException if there is an error
 932      * in the underlying protocol, such as a TCP error.
 933      *
 934      * @param size the size to which to set the receive buffer
 935      * size. This value must be greater than 0.
 936      *
 937      * @throws    IllegalArgumentException if the
 938      * value is 0 or is negative.
 939      *
 940      * @since 1.4
 941      * @see #getReceiveBufferSize
 942      */
 943      public synchronized void setReceiveBufferSize (int size) throws SocketException {
 944         if (!(size > 0)) {
 945             throw new IllegalArgumentException("negative receive size");
 946         }
 947         if (isClosed())
 948             throw new SocketException("Socket is closed");
 949         getImpl().setOption(SocketOptions.SO_RCVBUF, size);
 950     }
 951 
 952     /**
 953      * Gets the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option
 954      * for this {@code ServerSocket}, that is the proposed buffer size that
 955      * will be used for Sockets accepted from this {@code ServerSocket}.
 956      *
 957      * <p>Note, the value actually set in the accepted socket is determined by
 958      * calling {@link Socket#getReceiveBufferSize()}.
 959      * @return the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF}
 960      *         option for this {@code Socket}.
 961      * @throws    SocketException if there is an error
 962      *            in the underlying protocol, such as a TCP error.
 963      * @see #setReceiveBufferSize(int)
 964      * @since 1.4
 965      */
 966     public synchronized int getReceiveBufferSize()
 967     throws SocketException{
 968         if (isClosed())
 969             throw new SocketException("Socket is closed");
 970         int result = 0;
 971         Object o = getImpl().getOption(SocketOptions.SO_RCVBUF);
 972         if (o instanceof Integer) {
 973             result = ((Integer)o).intValue();
 974         }
 975         return result;
 976     }
 977 
 978     /**
 979      * Sets performance preferences for this ServerSocket.
 980      *
 981      * <p> Sockets use the TCP/IP protocol by default.  Some implementations


< prev index next >