1 /* ServerSocket.java -- Class for implementing server side sockets
2 Copyright (C) 1998, 1999, 2000, 2002 Free Software Foundation, Inc.
4 This file is part of GNU Classpath.
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING. If not, write to the
18 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library. Thus, the terms and
23 conditions of the GNU General Public License cover the whole
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module. An independent module is a module which is not derived from
33 or based on this library. If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so. If you do not wish to do so, delete this
36 exception statement from your version. */
40 import java.io.IOException;
41 import java.nio.channels.IllegalBlockingModeException;
42 import java.nio.channels.ServerSocketChannel;
44 /* Written using on-line Java Platform 1.2 API Specification.
45 * Status: I believe all methods are implemented.
49 * This class models server side sockets. The basic model is that the
50 * server socket is created and bound to some well known port. It then
51 * listens for and accepts connections. At that point the client and
52 * server sockets are ready to communicate with one another utilizing
53 * whatever application layer protocol they desire.
55 * As with the <code>Socket</code> class, most instance methods of this class
56 * simply redirect their calls to an implementation class.
58 * @author Aaron M. Renn (arenn@urbanophile.com)
59 * @author Per Bothner (bothner@cygnus.com)
61 public class ServerSocket
64 * This is the user defined SocketImplFactory, if one is supplied
66 private static SocketImplFactory factory;
69 * This is the SocketImp object to which most instance methods in this
70 * class are redirected
72 private SocketImpl impl;
75 * ServerSocketChannel of this ServerSocket. This channel only exists
76 * when the socket is created by ServerSocketChannel.open().
78 private ServerSocketChannel ch;
80 private boolean closed = false;
83 * Constructor that simply sets the implementation.
85 * @exception IOException If an error occurs
87 * @specnote This constructor is public since JDK 1.4
89 public ServerSocket() throws IOException
92 impl = factory.createSocketImpl();
94 impl = new PlainSocketImpl();
100 * Creates a server socket and binds it to the specified port. If the
101 * port number is 0, a random free port will be chosen. The pending
102 * connection queue on this socket will be set to 50.
104 * @param port The port number to bind to
106 * @exception IOException If an error occurs
107 * @exception SecurityException If a security manager exists and its
108 * checkListen method doesn't allow the operation
110 public ServerSocket (int port)
117 * Creates a server socket and binds it to the specified port. If the
118 * port number is 0, a random free port will be chosen. The pending
119 * connection queue on this socket will be set to the value passed as
122 * @param port The port number to bind to
123 * @param backlog The length of the pending connection queue
125 * @exception IOException If an error occurs
126 * @exception SecurityException If a security manager exists and its
127 * checkListen method doesn't allow the operation
129 public ServerSocket (int port, int backlog)
132 this(port, backlog, null);
136 * Creates a server socket and binds it to the specified port. If the
137 * port number is 0, a random free port will be chosen. The pending
138 * connection queue on this socket will be set to the value passed as
139 * backlog. The third argument specifies a particular local address to
140 * bind t or null to bind to all local address.
142 * @param port The port number to bind to
143 * @param backlog The length of the pending connection queue
144 * @param bindAddr The address to bind to, or null to bind to all addresses
146 * @exception IOException If an error occurs
147 * @exception SecurityException If a security manager exists and its
148 * checkListen method doesn't allow the operation
152 public ServerSocket (int port, int backlog, InetAddress bindAddr)
158 throw new IOException("Cannot initialize Socket implementation");
160 SecurityManager s = System.getSecurityManager();
164 if (bindAddr == null)
165 bindAddr = InetAddress.ANY_IF;
168 impl.bind(bindAddr, port);
169 impl.listen(backlog);
173 * Binds the server socket to a specified socket address
175 * @param endpoint The socket address to bind to
177 * @exception IOException If an error occurs
178 * @exception IllegalArgumentException If address type is not supported
179 * @exception SecurityException If a security manager exists and its
180 * checkListen method doesn't allow the operation
184 public void bind (SocketAddress endpoint)
191 * Binds the server socket to a specified socket address
193 * @param endpoint The socket address to bind to
194 * @param backlog The length of the pending connection queue
196 * @exception IOException If an error occurs
197 * @exception IllegalArgumentException If address type is not supported
198 * @exception SecurityException If a security manager exists and its
199 * checkListen method doesn't allow the operation
203 public void bind (SocketAddress endpoint, int backlog) throws IOException
206 throw new SocketException ("ServerSocket is closed");
209 throw new IOException ("Cannot initialize Socket implementation");
211 if (! (endpoint instanceof InetSocketAddress))
212 throw new IllegalArgumentException ("Address type not supported");
214 InetSocketAddress tmp = (InetSocketAddress) endpoint;
216 SecurityManager s = System.getSecurityManager ();
218 s.checkListen (tmp.getPort ());
220 impl.bind (tmp.getAddress (), tmp.getPort ());
221 impl.listen(backlog);
225 * This method returns the local address to which this socket is bound
227 * @return The socket's local address
229 public InetAddress getInetAddress()
233 return (InetAddress) impl.getOption (SocketOptions.SO_BINDADDR);
235 catch (SocketException e)
242 * This method returns the local port number to which this socket is bound
244 * @return The socket's port number
246 public int getLocalPort()
248 return impl.getLocalPort();
252 * Returns the local socket address
256 public SocketAddress getLocalSocketAddress()
258 InetAddress addr = getInetAddress();
261 return new InetSocketAddress (getInetAddress(), getLocalPort());
267 * Accepts a new connection and returns a connected <code>Socket</code>
268 * instance representing that connection. This method will block until a
269 * connection is available.
271 * @exception IOException If an error occurs
272 * @exception SecurityException If a security manager exists and its
273 * checkListen method doesn't allow the operation
274 * @exception IllegalBlockingModeException If this socket has an associated
275 * channel, and the channel is in non-blocking mode
276 * @exception SocketTimeoutException If a timeout was previously set with
277 * setSoTimeout and the timeout has been reached
279 public Socket accept () throws IOException
282 throw new IOException ("Cannot initialize Socket implementation");
284 SecurityManager sm = System.getSecurityManager ();
286 sm.checkListen (impl.getLocalPort ());
288 Socket s = new Socket();
295 * This protected method is used to help subclasses override
296 * <code>ServerSocket.accept()</code>. The passed in socket will be
297 * connected when this method returns.
299 * @param socket The socket that is used for the accepted connection
301 * @exception IOException If an error occurs
302 * @exception IllegalBlockingModeException If this socket has an associated
303 * channel, and the channel is in non-blocking mode
307 protected final void implAccept (Socket s)
310 if (ch != null && !ch.isBlocking())
311 throw new IllegalBlockingModeException();
317 * Closes this socket and stops listening for connections
319 * @exception IOException If an error occurs
321 public void close () throws IOException
333 * Returns the unique ServerSocketChannel object
334 * associated with this socket, if any.
336 * The socket only has a ServerSocketChannel if its created
337 * by ServerSocketChannel.open.
341 public ServerSocketChannel getChannel()
347 * Returns true then the socket is bound, otherwise false
351 public boolean isBound()
355 Object bindaddr = impl.getOption (SocketOptions.SO_BINDADDR);
357 catch (SocketException e)
366 * Returns true if the socket is closed, otherwise false
370 public boolean isClosed()
376 * Sets the value of SO_TIMEOUT. A value of 0 implies that SO_TIMEOUT is
377 * disabled (ie, operations never time out). This is the number of
378 * milliseconds a socket operation can block before an
379 * InterruptedIOException is thrown.
381 * @param timeout The new SO_TIMEOUT value
383 * @exception SocketException If an error occurs
387 public void setSoTimeout (int timeout) throws SocketException
390 throw new IllegalArgumentException("SO_TIMEOUT value must be >= 0");
392 impl.setOption(SocketOptions.SO_TIMEOUT, new Integer(timeout));
396 * Retrieves the current value of the SO_TIMEOUT setting. A value of 0
397 * implies that SO_TIMEOUT is disabled (ie, operations never time out).
398 * This is the number of milliseconds a socket operation can block before
399 * an InterruptedIOException is thrown.
401 * @return The value of SO_TIMEOUT
403 * @exception IOException If an error occurs
407 public int getSoTimeout () throws IOException
409 Object timeout = impl.getOption(SocketOptions.SO_TIMEOUT);
411 if (!(timeout instanceof Integer))
412 throw new IOException("Internal Error");
414 return ((Integer)timeout).intValue();
418 * Enables/Disables the SO_REUSEADDR option
420 * @exception SocketException If an error occurs
424 public void setReuseAddress (boolean on)
425 throws SocketException
428 throw new SocketException ("Cannot initialize Socket implementation");
430 impl.setOption (SocketOptions.SO_REUSEADDR, new Boolean (on));
434 * Checks if the SO_REUSEADDR option is enabled
436 * @exception SocketException If an error occurs
440 public boolean getReuseAddress()
441 throws SocketException
444 throw new SocketException ("Cannot initialize Socket implementation");
446 Object reuseaddr = impl.getOption (SocketOptions.SO_REUSEADDR);
448 if (!(reuseaddr instanceof Boolean))
449 throw new SocketException ("Internal Error");
451 return ((Boolean) reuseaddr).booleanValue ();
455 * This method sets the value for the system level socket option
456 * SO_RCVBUF to the specified value. Note that valid values for this
457 * option are specific to a given operating system.
459 * @param size The new receive buffer size.
461 * @exception SocketException If an error occurs or Socket is not connected
462 * @exception IllegalArgumentException If size is 0 or negative
466 public void setReceiveBufferSize (int size)
467 throws SocketException
470 throw new SocketException ("Not connected");
473 throw new IllegalArgumentException ("SO_RCVBUF value must be > 0");
475 impl.setOption (SocketOptions.SO_RCVBUF, new Integer (size));
479 * This method returns the value of the system level socket option
480 * SO_RCVBUF, which is used by the operating system to tune buffer
481 * sizes for data transfers.
483 * @return The receive buffer size.
485 * @exception SocketException If an error occurs or Socket is not connected
489 public int getReceiveBufferSize ()
490 throws SocketException
493 throw new SocketException ("Not connected");
495 Object buf = impl.getOption (SocketOptions.SO_RCVBUF);
497 if (!(buf instanceof Integer))
498 throw new SocketException ("Internal Error: Unexpected type");
500 return ((Integer) buf).intValue ();
504 * Returns the value of this socket as a <code>String</code>.
506 * @return This socket represented as a <code>String</code>.
508 public String toString ()
510 return "ServerSocket" + impl.toString();
516 * Sets the <code>SocketImplFactory</code> for all
517 * <code>ServerSocket</code>'s. This may only be done
518 * once per virtual machine. Subsequent attempts will generate an
519 * exception. Note that a <code>SecurityManager</code> check is made prior
520 * to setting the factory. If insufficient privileges exist to set the
521 * factory, an exception will be thrown
523 * @exception SecurityException If this operation is not allowed by the
524 * <code>SecurityManager</code>.
525 * @exception SocketException If the factory object is already defined
526 * @exception IOException If any other error occurs
528 public static synchronized void setSocketFactory (SocketImplFactory fac)