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