2003-06-08 Michael Koch <konqueror@gmx.de>
[gcc.git] / libjava / java / net / Socket.java
1 /* Socket.java -- Client socket implementation
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.*;
41 import java.nio.channels.SocketChannel;
42 import java.nio.channels.IllegalBlockingModeException;
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 a client site socket. A socket is a TCP/IP endpoint
50 * for network communications conceptually similar to a file handle.
51 * <p>
52 * This class does not actually do any work. Instead, it redirects all of
53 * its calls to a socket implementation object which implements the
54 * <code>SocketImpl</code> interface. The implementation class is
55 * instantiated by factory class that implements the
56 * <code>SocketImplFactory interface</code>. A default
57 * factory is provided, however the factory may be set by a call to
58 * the <code>setSocketImplFactory</code> method. Note that this may only be
59 * done once per virtual machine. If a subsequent attempt is made to set the
60 * factory, a <code>SocketException</code> will be thrown.
61 *
62 * @author Aaron M. Renn (arenn@urbanophile.com)
63 * @author Per Bothner (bothner@cygnus.com)
64 */
65 public class Socket
66 {
67
68 // Class Variables
69
70 /**
71 * This is the user SocketImplFactory for this class. If this variable is
72 * null, a default factory is used.
73 */
74 static SocketImplFactory factory;
75
76 // Instance Variables
77
78 /**
79 * The implementation object to which calls are redirected
80 */
81 SocketImpl impl;
82
83 private boolean inputShutdown;
84 private boolean outputShutdown;
85
86 SocketChannel ch; // this field must have been set if created by SocketChannel
87
88 private boolean closed = false;
89
90 // Constructors
91
92 /**
93 * Initializes a new instance of <code>Socket</code> object without
94 * connecting to a remote host. This useful for subclasses of socket that
95 * might want this behavior.
96 *
97 * @specnote This constructor is public since JDK 1.4
98 * @since 1.1
99 */
100 public Socket ()
101 {
102 if (factory != null)
103 impl = factory.createSocketImpl();
104 else
105 impl = new PlainSocketImpl();
106
107 inputShutdown = false;
108 outputShutdown = false;
109 }
110
111 /**
112 * Initializes a new instance of <code>Socket</code> object without
113 * connecting to a remote host. This is useful for subclasses of socket
114 * that might want this behavior.
115 * <p>
116 * Additionally, this socket will be created using the supplied
117 * implementation class instead the default class or one returned by a
118 * factory. This value can be <code>null</code>, but if it is, all instance
119 * methods in <code>Socket</code> should be overridden because most of them
120 * rely on this value being populated.
121 *
122 * @param impl The <code>SocketImpl</code> to use for this
123 * <code>Socket</code>
124 *
125 * @exception SocketException If an error occurs
126 *
127 * @since 1.1
128 */
129 protected Socket (SocketImpl impl) throws SocketException
130 {
131 this.impl = impl;
132 this.inputShutdown = false;
133 this.outputShutdown = false;
134 }
135
136 /**
137 * Initializes a new instance of <code>Socket</code> and connects to the
138 * hostname and port specified as arguments.
139 *
140 * @param host The name of the host to connect to
141 * @param port The port number to connect to
142 *
143 * @exception UnknownHostException If the hostname cannot be resolved to a
144 * network address.
145 * @exception IOException If an error occurs
146 * @exception SecurityException If a security manager exists and its
147 * checkConnect method doesn't allow the operation
148 */
149 public Socket (String host, int port)
150 throws UnknownHostException, IOException
151 {
152 this(InetAddress.getByName(host), port, null, 0, true);
153 }
154
155 /**
156 * Initializes a new instance of <code>Socket</code> and connects to the
157 * address and port number specified as arguments.
158 *
159 * @param address The address to connect to
160 * @param port The port number to connect to
161 *
162 * @exception IOException If an error occurs
163 * @exception SecurityException If a security manager exists and its
164 * checkConnect method doesn't allow the operation
165 */
166 public Socket (InetAddress address, int port)
167 throws IOException
168 {
169 this(address, port, null, 0, true);
170 }
171
172 /**
173 * Initializes a new instance of <code>Socket</code> that connects to the
174 * named host on the specified port and binds to the specified local address
175 * and port.
176 *
177 * @param host The name of the remote host to connect to.
178 * @param port The remote port to connect to.
179 * @param loadAddr The local address to bind to.
180 * @param localPort The local port to bind to.
181 *
182 * @exception SecurityException If the <code>SecurityManager</code>
183 * exists and does not allow a connection to the specified host/port or
184 * binding to the specified local host/port.
185 * @exception IOException If a connection error occurs.
186 *
187 * @since 1.1
188 */
189 public Socket (String host, int port,
190 InetAddress localAddr, int localPort) throws IOException
191 {
192 this(InetAddress.getByName(host), port, localAddr, localPort, true);
193 }
194
195 /**
196 * Initializes a new instance of <code>Socket</code> and connects to the
197 * address and port number specified as arguments, plus binds to the
198 * specified local address and port.
199 *
200 * @param address The remote address to connect to
201 * @param port The remote port to connect to
202 * @param localAddr The local address to connect to
203 * @param localPort The local port to connect to
204 *
205 * @exception IOException If an error occurs
206 * @exception SecurityException If a security manager exists and its
207 * checkConnect method doesn't allow the operation
208 *
209 * @since 1.1
210 */
211 public Socket (InetAddress address, int port,
212 InetAddress localAddr, int localPort) throws IOException
213 {
214 this(address, port, localAddr, localPort, true);
215 }
216
217 /**
218 * Initializes a new instance of <code>Socket</code> and connects to the
219 * hostname and port specified as arguments. If the stream argument is set
220 * to <code>true</code>, then a stream socket is created. If it is
221 * <code>false</code>, a datagram socket is created.
222 *
223 * @param host The name of the host to connect to
224 * @param port The port to connect to
225 * @param stream <code>true</code> for a stream socket, <code>false</code>
226 * for a datagram socket
227 *
228 * @exception IOException If an error occurs
229 * @exception SecurityException If a security manager exists and its
230 * checkConnect method doesn't allow the operation
231 *
232 * @deprecated Use the <code>DatagramSocket</code> class to create
233 * datagram oriented sockets.
234 */
235 public Socket (String host, int port, boolean stream) throws IOException
236 {
237 this(InetAddress.getByName(host), port, null, 0, stream);
238 }
239
240 /**
241 * Initializes a new instance of <code>Socket</code> and connects to the
242 * address and port number specified as arguments. If the stream param is
243 * <code>true</code>, a stream socket will be created, otherwise a datagram
244 * socket is created.
245 *
246 * @param host The address to connect to
247 * @param port The port number to connect to
248 * @param stream <code>true</code> to create a stream socket,
249 * <code>false</code> to create a datagram socket.
250 *
251 * @exception IOException If an error occurs
252 * @exception SecurityException If a security manager exists and its
253 * checkConnect method doesn't allow the operation
254 *
255 * @deprecated Use the <code>DatagramSocket</code> class to create
256 * datagram oriented sockets.
257 */
258 public Socket (InetAddress host, int port, boolean stream) throws IOException
259 {
260 this(host, port, null, 0, stream);
261 }
262
263 /**
264 * This constructor is where the real work takes place. Connect to the
265 * specified address and port. Use default local values if not specified,
266 * otherwise use the local host and port passed in. Create as stream or
267 * datagram based on "stream" argument.
268 * <p>
269 *
270 * @param raddr The remote address to connect to
271 * @param rport The remote port to connect to
272 * @param laddr The local address to connect to
273 * @param lport The local port to connect to
274 * @param stream true for a stream socket, false for a datagram socket
275 *
276 * @exception IOException If an error occurs
277 * @exception SecurityException If a security manager exists and its
278 * checkConnect method doesn't allow the operation
279 */
280 private Socket(InetAddress raddr, int rport, InetAddress laddr, int lport,
281 boolean stream) throws IOException
282 {
283 this();
284
285 if (impl == null)
286 throw new IOException("Cannot initialize Socket implementation");
287
288 SecurityManager sm = System.getSecurityManager();
289 if (sm != null)
290 sm.checkConnect(raddr.getHostName(), rport);
291
292 // bind/connect socket
293 bind (new InetSocketAddress (laddr, lport));
294 connect (new InetSocketAddress (raddr, rport));
295
296 // FIXME: JCL p. 1586 says if localPort is unspecified, bind to any port,
297 // i.e. '0' and if localAddr is unspecified, use getLocalAddress() as
298 // that default. JDK 1.2 doc infers not to do a bind.
299 }
300
301 /**
302 * Binds the socket to the givent local address/port
303 *
304 * @param bindpoint The address/port to bind to
305 *
306 * @exception IOException If an error occurs
307 * @exception SecurityException If a security manager exists and its
308 * checkConnect method doesn't allow the operation
309 * @exception IllegalArgumentException If the address type is not supported
310 *
311 * @since 1.4
312 */
313 public void bind (SocketAddress bindpoint) throws IOException
314 {
315 if (closed)
316 throw new SocketException ("Socket is closed");
317
318 // XXX: JDK 1.4.1 API documentation says that if bindpoint is null the
319 // socket will be bound to an ephemeral port and a valid local address.
320 if (bindpoint == null)
321 bindpoint = new InetSocketAddress (InetAddress.ANY_IF, 0);
322
323 if ( !(bindpoint instanceof InetSocketAddress))
324 throw new IllegalArgumentException ();
325
326 InetSocketAddress tmp = (InetSocketAddress) bindpoint;
327
328 // create socket
329 impl.create (true);
330
331 // bind to address/port
332 try
333 {
334 impl.bind (tmp.getAddress(), tmp.getPort());
335 }
336 catch (IOException exception)
337 {
338 impl.close ();
339 throw exception;
340 }
341 catch (RuntimeException exception)
342 {
343 impl.close ();
344 throw exception;
345 }
346 catch (Error error)
347 {
348 impl.close ();
349 throw error;
350 }
351 }
352
353 /**
354 * Connects the socket with a remote address.
355 *
356 * @param endpoint The address to connect to
357 *
358 * @exception IOException If an error occurs
359 * @exception IllegalArgumentException If the addess type is not supported
360 * @exception IllegalBlockingModeException If this socket has an associated
361 * channel, and the channel is in non-blocking mode
362 *
363 * @since 1.4
364 */
365 public void connect (SocketAddress endpoint)
366 throws IOException
367 {
368 connect (endpoint, 0);
369 }
370
371 /**
372 * Connects the socket with a remote address. A timeout of zero is
373 * interpreted as an infinite timeout. The connection will then block
374 * until established or an error occurs.
375 *
376 * @param endpoint The address to connect to
377 *
378 * @exception IOException If an error occurs
379 * @exception IllegalArgumentException If the address type is not supported
380 * @exception IllegalBlockingModeException If this socket has an associated
381 * channel, and the channel is in non-blocking mode
382 * @exception SocketTimeoutException If the timeout is reached
383 *
384 * @since 1.4
385 */
386 public void connect (SocketAddress endpoint, int timeout)
387 throws IOException
388 {
389 if (closed)
390 throw new SocketException ("Socket is closed");
391
392 if (! (endpoint instanceof InetSocketAddress))
393 throw new IllegalArgumentException ("Address type not supported");
394
395 if (ch != null && !ch.isBlocking ())
396 throw new IllegalBlockingModeException ();
397
398 if (!isBound ())
399 bind (null);
400
401 try
402 {
403 impl.connect (endpoint, timeout);
404 }
405 catch (IOException exception)
406 {
407 impl.close ();
408 throw exception;
409 }
410 catch (RuntimeException exception)
411 {
412 impl.close ();
413 throw exception;
414 }
415 catch (Error error)
416 {
417 impl.close ();
418 throw error;
419 }
420 }
421
422 /**
423 * Returns the address of the remote end of the socket. If this socket
424 * is not connected, then <code>null</code> is returned.
425 *
426 * @return The remote address this socket is connected to
427 */
428 public InetAddress getInetAddress ()
429 {
430 if (impl != null)
431 return impl.getInetAddress();
432
433 return null;
434 }
435
436 /**
437 * Returns the local address to which this socket is bound. If this socket
438 * is not connected, then <code>null</code> is returned.
439 *
440 * @return The local address
441 *
442 * @since 1.1
443 */
444 public InetAddress getLocalAddress ()
445 {
446 if (impl == null)
447 return null;
448
449 InetAddress addr = null;
450 try
451 {
452 addr = (InetAddress)impl.getOption(SocketOptions.SO_BINDADDR);
453 }
454 catch(SocketException e)
455 {
456 // (hopefully) shouldn't happen
457 // throw new java.lang.InternalError
458 // ("Error in PlainSocketImpl.getOption");
459 return null;
460 }
461
462 // FIXME: According to libgcj, checkConnect() is supposed to be called
463 // before performing this operation. Problems: 1) We don't have the
464 // addr until after we do it, so we do a post check. 2). The docs I
465 // see don't require this in the Socket case, only DatagramSocket, but
466 // we'll assume they mean both.
467 SecurityManager sm = System.getSecurityManager();
468 if (sm != null)
469 sm.checkConnect(addr.getHostName(), getLocalPort());
470
471 return addr;
472 }
473
474 /**
475 * Returns the port number of the remote end of the socket connection. If
476 * this socket is not connected, then -1 is returned.
477 *
478 * @return The remote port this socket is connected to
479 */
480 public int getPort ()
481 {
482 if (impl != null)
483 return impl.getPort();
484
485 return -1;
486 }
487
488 /**
489 * Returns the local port number to which this socket is bound. If this
490 * socket is not connected, then -1 is returned.
491 *
492 * @return The local port
493 */
494 public int getLocalPort ()
495 {
496 if (impl != null)
497 return impl.getLocalPort();
498
499 return -1;
500 }
501
502 /**
503 * If the socket is already bound this returns the local SocketAddress,
504 * otherwise null
505 *
506 * @since 1.4
507 */
508 public SocketAddress getLocalSocketAddress()
509 {
510 InetAddress addr = getLocalAddress ();
511
512 if (addr == null)
513 return null;
514
515 return new InetSocketAddress (addr, impl.getLocalPort());
516 }
517
518 /**
519 * If the socket is already connected this returns the remote SocketAddress,
520 * otherwise null
521 *
522 * @since 1.4
523 */
524 public SocketAddress getRemoteSocketAddress()
525 {
526 if (!isConnected ())
527 return null;
528
529 return new InetSocketAddress (impl.getInetAddress (), impl.getPort ());
530 }
531
532 /**
533 * Returns an InputStream for reading from this socket.
534 *
535 * @return The InputStream object
536 *
537 * @exception IOException If an error occurs or Socket is not connected
538 */
539 public InputStream getInputStream () throws IOException
540 {
541 if (impl != null)
542 return(impl.getInputStream());
543
544 throw new IOException("Not connected");
545 }
546
547 /**
548 * Returns an OutputStream for writing to this socket.
549 *
550 * @return The OutputStream object
551 *
552 * @exception IOException If an error occurs or Socket is not connected
553 */
554 public OutputStream getOutputStream () throws IOException
555 {
556 if (impl != null)
557 return impl.getOutputStream();
558
559 throw new IOException("Not connected");
560 }
561
562 /**
563 * Sets the TCP_NODELAY option on the socket.
564 *
565 * @param on true to enable, false to disable
566 *
567 * @exception SocketException If an error occurs or Socket is not connected
568 *
569 * @since 1.1
570 */
571 public void setTcpNoDelay (boolean on) throws SocketException
572 {
573 if (impl == null)
574 throw new SocketException("Not connected");
575
576 impl.setOption(SocketOptions.TCP_NODELAY, new Boolean(on));
577 }
578
579 /**
580 * Tests whether or not the TCP_NODELAY option is set on the socket.
581 * Returns true if enabled, false if disabled. When on it disables the
582 * Nagle algorithm which means that packets are always send immediatly and
583 * never merged together to reduce network trafic.
584 *
585 * @return Whether or not TCP_NODELAY is set
586 *
587 * @exception SocketException If an error occurs or Socket not connected
588 *
589 * @since 1.1
590 */
591 public boolean getTcpNoDelay() throws SocketException
592 {
593 if (impl == null)
594 throw new SocketException("Not connected");
595
596 Object on = impl.getOption(SocketOptions.TCP_NODELAY);
597
598 if (on instanceof Boolean)
599 return(((Boolean)on).booleanValue());
600 else
601 throw new SocketException("Internal Error");
602 }
603
604 /**
605 * Sets the value of the SO_LINGER option on the socket. If the
606 * SO_LINGER option is set on a socket and there is still data waiting to
607 * be sent when the socket is closed, then the close operation will block
608 * until either that data is delivered or until the timeout period
609 * expires. The linger interval is specified in hundreths of a second
610 * (platform specific?)
611 *
612 * @param on true to enable SO_LINGER, false to disable
613 * @param linger The SO_LINGER timeout in hundreths of a second or -1 if
614 * SO_LINGER not set.
615 *
616 * @exception SocketException If an error occurs or Socket not connected
617 * @exception IllegalArgumentException If linger is negative
618 *
619 * @since 1.1
620 */
621 public void setSoLinger(boolean on, int linger) throws SocketException
622 {
623 if (impl == null)
624 throw new SocketException("No socket created");
625
626 if (on == true)
627 {
628 if (linger < 0)
629 throw new IllegalArgumentException("SO_LINGER must be >= 0");
630
631 if (linger > 65535)
632 linger = 65535;
633
634 impl.setOption(SocketOptions.SO_LINGER, new Integer(linger));
635 }
636 else
637 {
638 impl.setOption(SocketOptions.SO_LINGER, new Boolean(false));
639 }
640 }
641
642 /**
643 * Returns the value of the SO_LINGER option on the socket. If the
644 * SO_LINGER option is set on a socket and there is still data waiting to
645 * be sent when the socket is closed, then the close operation will block
646 * until either that data is delivered or until the timeout period
647 * expires. This method either returns the timeouts (in hundredths of
648 * of a second (platform specific?)) if SO_LINGER is set, or -1 if
649 * SO_LINGER is not set.
650 *
651 * @return The SO_LINGER timeout in hundreths of a second or -1
652 * if SO_LINGER not set
653 *
654 * @exception SocketException If an error occurs or Socket is not connected
655 *
656 * @since 1.1
657 */
658 public int getSoLinger() throws SocketException
659 {
660 if (impl == null)
661 throw new SocketException("Not connected");
662
663 Object linger = impl.getOption(SocketOptions.SO_LINGER);
664 if (linger instanceof Integer)
665 return(((Integer)linger).intValue());
666 else
667 return -1;
668 }
669
670 /**
671 * Sends urgent data through the socket
672 *
673 * @param data The data to send.
674 * Only the lowest eight bits of data are sent
675 *
676 * @exception IOException If an error occurs
677 *
678 * @since 1.4
679 */
680 public void sendUrgentData (int data) throws IOException
681 {
682 impl.sendUrgentData (data);
683 }
684
685 /**
686 * Enables/disables the SO_OOBINLINE option
687 *
688 * @param on True if SO_OOBLINE should be enabled
689 *
690 * @exception SocketException If an error occurs
691 *
692 * @since 1.4
693 */
694 public void setOOBInline (boolean on) throws SocketException
695 {
696 if (impl == null)
697 throw new SocketException("Not connected");
698
699 impl.setOption(SocketOptions.SO_OOBINLINE, new Boolean(on));
700 }
701
702 /**
703 * Returns the current setting of the SO_OOBINLINE option for this socket
704 *
705 * @exception SocketException If an error occurs
706 *
707 * @since 1.4
708 */
709 public boolean getOOBInline () throws SocketException
710 {
711 if (impl == null)
712 throw new SocketException("Not connected");
713
714 Object buf = impl.getOption(SocketOptions.SO_OOBINLINE);
715
716 if (buf instanceof Boolean)
717 return(((Boolean)buf).booleanValue());
718 else
719 throw new SocketException("Internal Error: Unexpected type");
720 }
721
722 /**
723 * Sets the value of the SO_TIMEOUT option on the socket. If this value
724 * is set, and an read/write is performed that does not complete within
725 * the timeout period, a short count is returned (or an EWOULDBLOCK signal
726 * would be sent in Unix if no data had been read). A value of 0 for
727 * this option implies that there is no timeout (ie, operations will
728 * block forever). On systems that have separate read and write timeout
729 * values, this method returns the read timeout. This
730 * value is in milliseconds.
731 *
732 * @param timeout The length of the timeout in milliseconds, or
733 * 0 to indicate no timeout.
734 *
735 * @exception SocketException If an error occurs or Socket not connected
736 *
737 * @since 1.1
738 */
739 public synchronized void setSoTimeout (int timeout) throws SocketException
740 {
741 if (impl == null)
742 throw new SocketException("Not connected");
743
744 if (timeout < 0)
745 throw new IllegalArgumentException("SO_TIMEOUT value must be >= 0");
746
747 impl.setOption(SocketOptions.SO_TIMEOUT, new Integer(timeout));
748 }
749
750 /**
751 * Returns the value of the SO_TIMEOUT option on the socket. If this value
752 * is set, and an read/write is performed that does not complete within
753 * the timeout period, a short count is returned (or an EWOULDBLOCK signal
754 * would be sent in Unix if no data had been read). A value of 0 for
755 * this option implies that there is no timeout (ie, operations will
756 * block forever). On systems that have separate read and write timeout
757 * values, this method returns the read timeout. This
758 * value is in thousandths of a second (implementation specific?).
759 *
760 * @return The length of the timeout in thousandth's of a second or 0
761 * if not set
762 *
763 * @exception SocketException If an error occurs or Socket not connected
764 *
765 * @since 1.1
766 */
767 public synchronized int getSoTimeout () throws SocketException
768 {
769 if (impl == null)
770 throw new SocketException("Not connected");
771
772 Object timeout = impl.getOption(SocketOptions.SO_TIMEOUT);
773 if (timeout instanceof Integer)
774 return(((Integer)timeout).intValue());
775 else
776 return 0;
777 }
778
779 /**
780 * This method sets the value for the system level socket option
781 * SO_SNDBUF to the specified value. Note that valid values for this
782 * option are specific to a given operating system.
783 *
784 * @param size The new send buffer size.
785 *
786 * @exception SocketException If an error occurs or Socket not connected
787 * @exception IllegalArgumentException If size is 0 or negative
788 *
789 * @since 1.2
790 */
791 public void setSendBufferSize (int size) throws SocketException
792 {
793 if (impl == null)
794 throw new SocketException("Not connected");
795
796 if (size <= 0)
797 throw new IllegalArgumentException("SO_SNDBUF value must be > 0");
798
799 impl.setOption(SocketOptions.SO_SNDBUF, new Integer(size));
800 }
801
802 /**
803 * This method returns the value of the system level socket option
804 * SO_SNDBUF, which is used by the operating system to tune buffer
805 * sizes for data transfers.
806 *
807 * @return The send buffer size.
808 *
809 * @exception SocketException If an error occurs or socket not connected
810 *
811 * @since 1.2
812 */
813 public int getSendBufferSize () throws SocketException
814 {
815 if (impl == null)
816 throw new SocketException("Not connected");
817
818 Object buf = impl.getOption(SocketOptions.SO_SNDBUF);
819
820 if (buf instanceof Integer)
821 return(((Integer)buf).intValue());
822 else
823 throw new SocketException("Internal Error: Unexpected type");
824 }
825
826 /**
827 * This method sets the value for the system level socket option
828 * SO_RCVBUF to the specified value. Note that valid values for this
829 * option are specific to a given operating system.
830 *
831 * @param size The new receive buffer size.
832 *
833 * @exception SocketException If an error occurs or Socket is not connected
834 * @exception IllegalArgumentException If size is 0 or negative
835 *
836 * @since 1.2
837 */
838 public void setReceiveBufferSize (int size) throws SocketException
839 {
840 if (impl == null)
841 throw new SocketException("Not connected");
842
843 if (size <= 0)
844 throw new IllegalArgumentException("SO_RCVBUF value must be > 0");
845
846 impl.setOption(SocketOptions.SO_RCVBUF, new Integer(size));
847 }
848
849 /**
850 * This method returns the value of the system level socket option
851 * SO_RCVBUF, which is used by the operating system to tune buffer
852 * sizes for data transfers.
853 *
854 * @return The receive buffer size.
855 *
856 * @exception SocketException If an error occurs or Socket is not connected
857 *
858 * @since 1.2
859 */
860 public int getReceiveBufferSize () throws SocketException
861 {
862 if (impl == null)
863 throw new SocketException("Not connected");
864
865 Object buf = impl.getOption(SocketOptions.SO_RCVBUF);
866
867 if (buf instanceof Integer)
868 return(((Integer)buf).intValue());
869 else
870 throw new SocketException("Internal Error: Unexpected type");
871 }
872
873 /**
874 * This method sets the value for the socket level socket option
875 * SO_KEEPALIVE.
876 *
877 * @param on True if SO_KEEPALIVE should be enabled
878 *
879 * @exception SocketException If an error occurs or Socket is not connected
880 *
881 * @since 1.3
882 */
883 public void setKeepAlive (boolean on) throws SocketException
884 {
885 if (impl == null)
886 throw new SocketException("Not connected");
887
888 impl.setOption(SocketOptions.SO_KEEPALIVE, new Boolean(on));
889 }
890
891 /**
892 * This method returns the value of the socket level socket option
893 * SO_KEEPALIVE.
894 *
895 * @return The setting
896 *
897 * @exception SocketException If an error occurs or Socket is not connected
898 *
899 * @since 1.3
900 */
901 public boolean getKeepAlive () throws SocketException
902 {
903 if (impl == null)
904 throw new SocketException("Not connected");
905
906 Object buf = impl.getOption(SocketOptions.SO_KEEPALIVE);
907
908 if (buf instanceof Boolean)
909 return(((Boolean)buf).booleanValue());
910 else
911 throw new SocketException("Internal Error: Unexpected type");
912 }
913
914 /**
915 * Closes the socket.
916 *
917 * @exception IOException If an error occurs
918 */
919 public synchronized void close () throws IOException
920 {
921 if (impl != null)
922 impl.close();
923
924 if (ch != null)
925 ch.close();
926
927 closed = true;
928 }
929
930 /**
931 * Converts this <code>Socket</code> to a <code>String</code>.
932 *
933 * @return The <code>String</code> representation of this <code>Socket</code>
934 */
935 public String toString ()
936 {
937 return("Socket " + impl);
938 }
939
940 // Class Methods
941
942 /**
943 * Sets the <code>SocketImplFactory</code>. This may be done only once per
944 * virtual machine. Subsequent attempts will generate a
945 * <code>SocketException</code>. Note that a <code>SecurityManager</code>
946 * check is made prior to setting the factory. If
947 * insufficient privileges exist to set the factory, then an
948 * <code>IOException</code> will be thrown.
949 *
950 * @exception SecurityException If the <code>SecurityManager</code> does
951 * not allow this operation.
952 * @exception SocketException If the SocketImplFactory is already defined
953 * @exception IOException If any other error occurs
954 */
955 public static synchronized void setSocketImplFactory (SocketImplFactory fac)
956 throws IOException
957 {
958 // See if already set
959 if (factory != null)
960 throw new SocketException("SocketImplFactory already defined");
961
962 // Check permissions
963 SecurityManager sm = System.getSecurityManager();
964 if (sm != null)
965 sm.checkSetFactory();
966
967 if (fac == null)
968 throw new SocketException("SocketImplFactory cannot be null");
969
970 factory = fac;
971 }
972
973 /**
974 * Closes the input side of the socket stream.
975 *
976 * @exception IOException If an error occurs.
977 *
978 * @since 1.3
979 */
980 public void shutdownInput() throws IOException
981 {
982 if (impl != null)
983 impl.shutdownInput();
984
985 inputShutdown = true;
986 }
987
988 /**
989 * Closes the output side of the socket stream.
990 *
991 * @exception IOException If an error occurs.
992 *
993 * @since 1.3
994 */
995 public void shutdownOutput() throws IOException
996 {
997 if (impl != null)
998 impl.shutdownOutput();
999
1000 outputShutdown = true;
1001 }
1002
1003 /**
1004 * Returns the socket channel associated with this socket.
1005 *
1006 * It returns null if no associated socket exists.
1007 *
1008 * @since 1.4
1009 */
1010 public SocketChannel getChannel()
1011 {
1012 return ch;
1013 }
1014
1015 /**
1016 * Checks if the SO_REUSEADDR option is enabled
1017 *
1018 * @exception SocketException If an error occurs
1019 *
1020 * @since 1.4
1021 */
1022 public boolean getReuseAddress () throws SocketException
1023 {
1024 if (impl == null)
1025 throw new SocketException ("Cannot initialize Socket implementation");
1026
1027 Object reuseaddr = impl.getOption (SocketOptions.SO_REUSEADDR);
1028
1029 if (!(reuseaddr instanceof Boolean))
1030 throw new SocketException ("Internal Error");
1031
1032 return ((Boolean) reuseaddr).booleanValue ();
1033 }
1034
1035 /**
1036 * Enables/Disables the SO_REUSEADDR option
1037 *
1038 * @exception SocketException If an error occurs
1039 *
1040 * @since 1.4
1041 */
1042 public void setReuseAddress (boolean on) throws SocketException
1043 {
1044 if (impl == null)
1045 throw new SocketException ("Cannot initialize Socket implementation");
1046
1047 impl.setOption (SocketOptions.SO_REUSEADDR, new Boolean (on));
1048 }
1049
1050 /**
1051 * Returns the current traffic class
1052 *
1053 * @exception SocketException If an error occurs
1054 *
1055 * @see Socket#setTrafficClass(int tc)
1056 *
1057 * @since 1.4
1058 */
1059 public int getTrafficClass () throws SocketException
1060 {
1061 if (impl == null)
1062 throw new SocketException ("Cannot initialize Socket implementation");
1063
1064 Object obj = impl.getOption(SocketOptions.IP_TOS);
1065
1066 if (obj instanceof Integer)
1067 return ((Integer) obj).intValue ();
1068 else
1069 throw new SocketException ("Unexpected type");
1070 }
1071
1072 /**
1073 * Sets the traffic class value
1074 *
1075 * @param tc The traffic class
1076 *
1077 * @exception SocketException If an error occurs
1078 * @exception IllegalArgumentException If tc value is illegal
1079 *
1080 * @see Socket#getTrafficClass()
1081 *
1082 * @since 1.4
1083 */
1084 public void setTrafficClass (int tc) throws SocketException
1085 {
1086 if (impl == null)
1087 throw new SocketException ("Cannot initialize Socket implementation");
1088
1089 if (tc < 0 || tc > 255)
1090 throw new IllegalArgumentException();
1091
1092 impl.setOption (SocketOptions.IP_TOS, new Integer (tc));
1093 }
1094
1095 /**
1096 * Checks if the socket is connected
1097 *
1098 * @since 1.4
1099 */
1100 public boolean isConnected ()
1101 {
1102 return impl.getInetAddress () != null;
1103 }
1104
1105 /**
1106 * Checks if the socket is already bound.
1107 *
1108 * @since 1.4
1109 */
1110 public boolean isBound ()
1111 {
1112 return getLocalAddress () != null;
1113 }
1114
1115 /**
1116 * Checks if the socket is closed.
1117 *
1118 * @since 1.4
1119 */
1120 public boolean isClosed ()
1121 {
1122 return closed;
1123 }
1124
1125 /**
1126 * Checks if the socket's input stream is shutdown
1127 *
1128 * @since 1.4
1129 */
1130 public boolean isInputShutdown ()
1131 {
1132 return inputShutdown;
1133 }
1134
1135 /**
1136 * Checks if the socket's output stream is shutdown
1137 *
1138 * @since 1.4
1139 */
1140 public boolean isOutputShutdown ()
1141 {
1142 return outputShutdown;
1143 }
1144 }