2003-01-10 Michael Koch <konqueror@gmx.de>
[platform/upstream/gcc.git] / libjava / java / net / ServerSocket.java
1 /* ServerSocket.java -- Class for implementing server side sockets
2    Copyright (C) 1998, 1999, 2000, 2002 Free Software Foundation, Inc.
3
4 This file is part of GNU Classpath.
5
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)
9 any later version.
10  
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.
15
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
19 02111-1307 USA.
20
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
24 combination.
25
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. */
37
38 package java.net;
39
40 import java.io.IOException;
41 import java.nio.channels.IllegalBlockingModeException;
42 import java.nio.channels.ServerSocketChannel;
43
44 /* Written using on-line Java Platform 1.2 API Specification.
45  * Status:  I believe all methods are implemented.
46  */
47
48 /**
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.
54  *
55  * As with the <code>Socket</code> class, most instance methods of this class 
56  * simply redirect their calls to an implementation class.
57  *
58  * @author Aaron M. Renn (arenn@urbanophile.com)
59  * @author Per Bothner (bothner@cygnus.com)
60  */
61 public class ServerSocket
62 {
63   /**
64    * This is the user defined SocketImplFactory, if one is supplied
65    */
66   private static SocketImplFactory factory;
67
68   /**
69    * This is the SocketImp object to which most instance methods in this
70    * class are redirected
71    */
72   private SocketImpl impl;
73
74   /**
75    * ServerSocketChannel of this ServerSocket. This channel only exists
76    * when the socket is created by ServerSocketChannel.open().
77    */
78   private ServerSocketChannel ch;
79
80   private boolean closed = false;
81   
82   /**
83    * Constructor that simply sets the implementation.
84    * 
85    * @exception IOException If an error occurs
86    *
87    * @specnote This constructor is public since JDK 1.4
88    */
89   public ServerSocket() throws IOException
90   {
91     if (factory != null)
92       impl = factory.createSocketImpl();
93     else
94       impl = new PlainSocketImpl();
95
96     impl.create(true);
97   }
98
99   /**
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.
103    *
104    * @param port The port number to bind to
105    * 
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
109    */
110   public ServerSocket (int port)
111     throws IOException
112   {
113     this(port, 50);
114   }
115
116   /**
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
120    * arg2.
121    *
122    * @param port The port number to bind to
123    * @param backlog The length of the pending connection queue
124    *
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
128    */
129   public ServerSocket (int port, int backlog)
130     throws IOException
131   {
132     this(port, backlog, null);
133   }
134
135   /**
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.
141    *
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
145    *
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
149    *
150    * @since 1.1
151    */
152   public ServerSocket (int port, int backlog, InetAddress bindAddr)
153     throws IOException
154   {
155     this();
156
157     if (impl == null)
158       throw new IOException("Cannot initialize Socket implementation");
159
160     SecurityManager s = System.getSecurityManager();
161     if (s != null)
162       s.checkListen(port);
163
164     if (bindAddr == null)
165       bindAddr = InetAddress.ANY_IF;
166
167     impl.create(true);
168     impl.bind(bindAddr, port);
169     impl.listen(backlog);
170   }
171
172   /**
173    * Binds the server socket to a specified socket address
174    *
175    * @param endpoint The socket address to bind to
176    *
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
181    * 
182    * @since 1.4
183    */
184   public void bind (SocketAddress endpoint)
185     throws IOException
186   {
187     bind (endpoint, 50);
188   }
189  
190   /**
191    * Binds the server socket to a specified socket address
192    *
193    * @param endpoint The socket address to bind to
194    * @param backlog The length of the pending connection queue
195    * 
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
200    *
201    * @since 1.4
202    */
203   public void bind (SocketAddress endpoint, int backlog) throws IOException
204   {
205     if (closed)
206       throw new SocketException ("ServerSocket is closed");
207     
208     if (impl == null)
209       throw new IOException ("Cannot initialize Socket implementation");
210
211     if (! (endpoint instanceof InetSocketAddress))
212       throw new IllegalArgumentException ("Address type not supported");
213
214     InetSocketAddress tmp = (InetSocketAddress) endpoint;
215     
216     SecurityManager s = System.getSecurityManager ();
217     if (s != null)
218       s.checkListen (tmp.getPort ());
219
220     impl.bind (tmp.getAddress (), tmp.getPort ());
221     impl.listen(backlog);
222   }
223   
224   /**
225    * This method returns the local address to which this socket is bound
226    *
227    * @return The socket's local address
228    */
229   public InetAddress getInetAddress()
230   {
231     try
232       {
233         return (InetAddress) impl.getOption (SocketOptions.SO_BINDADDR);
234       }
235     catch (SocketException e)
236       {
237         return null;
238       }
239   }
240
241   /**
242    * This method returns the local port number to which this socket is bound
243    *
244    * @return The socket's port number
245    */
246   public int getLocalPort()
247   {
248     return impl.getLocalPort();
249   }
250
251   /**
252    * Returns the local socket address
253    *
254    * @since 1.4
255    */
256   public SocketAddress getLocalSocketAddress()
257   {
258     InetAddress addr = getInetAddress();
259
260     if (addr != null)
261       return new InetSocketAddress (getInetAddress(), getLocalPort());
262
263     return null;
264   }
265
266   /**
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.
270    *
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
278    */
279   public Socket accept () throws IOException
280   {
281     if (impl == null)
282       throw new IOException ("Cannot initialize Socket implementation");
283
284     SecurityManager sm = System.getSecurityManager ();
285     if (sm != null)
286       sm.checkListen (impl.getLocalPort ());
287
288     Socket s = new Socket();
289     implAccept (s);
290
291     return s;
292   }
293
294   /**
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.
298    *
299    * @param socket The socket that is used for the accepted connection
300    *
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
304    *
305    * @since 1.1
306    */
307   protected final void implAccept (Socket s)
308     throws IOException
309   {
310     if (ch != null && !ch.isBlocking())
311       throw new IllegalBlockingModeException();
312             
313     impl.accept(s.impl);
314   }
315
316   /**
317    * Closes this socket and stops listening for connections
318    *
319    * @exception IOException If an error occurs
320    */
321   public void close () throws IOException
322   {
323     if (impl != null)
324       impl.close ();
325
326     if (ch != null)
327       ch.close ();
328     
329     closed = true;
330   }
331
332   /**
333    * Returns the unique ServerSocketChannel object
334    * associated with this socket, if any.
335    *
336    * The socket only has a ServerSocketChannel if its created
337    * by ServerSocketChannel.open.
338    * 
339    * @since 1.4
340    */
341   public ServerSocketChannel getChannel()
342   {
343     return ch;
344   }
345
346   /**
347    * Returns true then the socket is bound, otherwise false
348    * 
349    * @since 1.4
350    */
351   public boolean isBound()
352   {
353     try
354       {
355         Object bindaddr = impl.getOption (SocketOptions.SO_BINDADDR);
356       }
357     catch (SocketException e)
358       {
359         return false;
360       }
361     
362     return true;
363   }
364
365   /**
366    * Returns true if the socket is closed, otherwise false
367    * 
368    * @since 1.4
369    */
370   public boolean isClosed()
371   {
372     return closed;
373   }
374
375   /**
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.
380    *
381    * @param timeout The new SO_TIMEOUT value
382    *
383    * @exception SocketException If an error occurs
384    *
385    * @since 1.1
386    */
387   public void setSoTimeout (int timeout) throws SocketException
388   {
389     if (timeout < 0)
390       throw new IllegalArgumentException("SO_TIMEOUT value must be >= 0");
391
392     impl.setOption(SocketOptions.SO_TIMEOUT, new Integer(timeout));
393   }
394
395   /**
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.
400    *
401    * @return The value of SO_TIMEOUT
402    *
403    * @exception IOException If an error occurs
404    *
405    * @since 1.1
406    */
407   public int getSoTimeout () throws IOException
408   {
409     Object timeout = impl.getOption(SocketOptions.SO_TIMEOUT);
410
411     if (!(timeout instanceof Integer))
412       throw new IOException("Internal Error");
413
414     return ((Integer)timeout).intValue();
415   }
416
417   /**
418    * Enables/Disables the SO_REUSEADDR option
419    * 
420    * @exception SocketException If an error occurs
421    * 
422    * @since 1.4
423    */
424   public void setReuseAddress (boolean on)
425     throws SocketException
426   {
427     if (impl == null)
428       throw new SocketException ("Cannot initialize Socket implementation");
429
430     impl.setOption (SocketOptions.SO_REUSEADDR, new Boolean (on));
431   }
432
433   /**
434    * Checks if the SO_REUSEADDR option is enabled
435    * 
436    * @exception SocketException If an error occurs
437    * 
438    * @since 1.4
439    */
440   public boolean getReuseAddress()
441     throws SocketException
442   {
443     if (impl == null)
444       throw new SocketException ("Cannot initialize Socket implementation");
445
446     Object reuseaddr = impl.getOption (SocketOptions.SO_REUSEADDR);
447
448     if (!(reuseaddr instanceof Boolean))
449       throw new SocketException ("Internal Error");
450     
451     return ((Boolean) reuseaddr).booleanValue ();
452   }
453
454   /**
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.
458    * 
459    * @param size The new receive buffer size.
460    * 
461    * @exception SocketException If an error occurs or Socket is not connected
462    * @exception IllegalArgumentException If size is 0 or negative
463    *
464    * @since 1.4
465    */
466   public void setReceiveBufferSize (int size)
467     throws SocketException
468   {
469     if (impl == null)
470       throw new SocketException ("Not connected");
471
472     if (size <= 0)
473       throw new IllegalArgumentException ("SO_RCVBUF value must be > 0");
474
475     impl.setOption (SocketOptions.SO_RCVBUF, new Integer (size));
476   }
477
478   /**
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.
482    * 
483    * @return The receive buffer size.
484    *             
485    * @exception SocketException If an error occurs or Socket is not connected
486    * 
487    * @since 1.4
488    */
489   public int getReceiveBufferSize ()
490     throws SocketException
491   {
492     if (impl == null)
493       throw new SocketException ("Not connected");
494
495     Object buf = impl.getOption (SocketOptions.SO_RCVBUF);
496
497     if (!(buf instanceof Integer))
498       throw new SocketException ("Internal Error: Unexpected type");
499     
500     return ((Integer) buf).intValue ();
501   }
502
503   /**
504    * Returns the value of this socket as a <code>String</code>. 
505    *
506    * @return This socket represented as a <code>String</code>.
507    */
508   public String toString ()
509   {
510     return "ServerSocket" + impl.toString();
511   }
512
513   // Class methods
514
515   /**
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
522    *
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
527    */
528   public static synchronized void setSocketFactory (SocketImplFactory fac)
529     throws IOException
530   {
531     factory = fac;
532   }
533 }