1 /* Socket.java -- Client socket implementation
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. */
42 /* Written using on-line Java Platform 1.2 API Specification.
43 * Status: I believe all methods are implemented.
47 * This class models a client site socket. A socket is a TCP/IP endpoint
48 * for network communications conceptually similar to a file handle.
50 * This class does not actually do any work. Instead, it redirects all of
51 * its calls to a socket implementation object which implements the
52 * <code>SocketImpl</code> interface. The implementation class is
53 * instantiated by factory class that implements the
54 * <code>SocketImplFactory interface</code>. A default
55 * factory is provided, however the factory may be set by a call to
56 * the <code>setSocketImplFactory</code> method. Note that this may only be
57 * done once per virtual machine. If a subsequent attempt is made to set the
58 * factory, a <code>SocketException</code> will be thrown.
60 * @author Aaron M. Renn (arenn@urbanophile.com)
61 * @author Per Bothner (bothner@cygnus.com)
69 * This is the user SocketImplFactory for this class. If this variable is
70 * null, a default factory is used.
72 static SocketImplFactory factory
;
77 * The implementation object to which calls are redirected
84 * Initializes a new instance of <code>Socket</code> object without
85 * connecting to a remote host. This useful for subclasses of socket that
86 * might want this behavior.
88 * @specnote This constructor is public since JDK 1.4
93 impl
= factory
.createSocketImpl();
95 impl
= new PlainSocketImpl();
99 * Initializes a new instance of <code>Socket</code> object without
100 * connecting to a remote host. This is useful for subclasses of socket
101 * that might want this behavior.
103 * Additionally, this socket will be created using the supplied
104 * implementation class instead the default class or one returned by a
105 * factory. This value can be <code>null</code>, but if it is, all instance
106 * methods in <code>Socket</code> should be overridden because most of them
107 * rely on this value being populated.
109 * @param impl The <code>SocketImpl</code> to use for this
110 * <code>Socket</code>
112 * @exception SocketException If an error occurs
114 protected Socket (SocketImpl impl
) throws SocketException
120 * Initializes a new instance of <code>Socket</code> and connects to the
121 * hostname and port specified as arguments.
123 * @param host The name of the host to connect to
124 * @param port The port number to connect to
126 * @exception UnknownHostException If the hostname cannot be resolved to a
128 * @exception IOException If an error occurs
130 public Socket (String host
, int port
)
131 throws UnknownHostException
, IOException
133 this(InetAddress
.getByName(host
), port
, null, 0, true);
137 * Initializes a new instance of <code>Socket</code> and connects to the
138 * address and port number specified as arguments.
140 * @param address The address to connect to
141 * @param port The port number to connect to
143 * @exception IOException If an error occurs
145 public Socket (InetAddress address
, int port
)
148 this(address
, port
, null, 0, true);
152 * Initializes a new instance of <code>Socket</code> that connects to the
153 * named host on the specified port and binds to the specified local address
156 * @param host The name of the remote host to connect to.
157 * @param port The remote port to connect to.
158 * @param loadAddr The local address to bind to.
159 * @param localPort The local port to bind to.
161 * @exception SecurityException If the <code>SecurityManager</code>
162 * exists and does not allow a connection to the specified host/port or
163 * binding to the specified local host/port.
164 * @exception IOException If a connection error occurs.
166 public Socket (String host
, int port
,
167 InetAddress localAddr
, int localPort
) throws IOException
169 this(InetAddress
.getByName(host
), port
, localAddr
, localPort
, true);
173 * Initializes a new instance of <code>Socket</code> and connects to the
174 * address and port number specified as arguments, plus binds to the
175 * specified local address and port.
177 * @param address The remote address to connect to
178 * @param port The remote port to connect to
179 * @param localAddr The local address to connect to
180 * @param localPort The local port to connect to
182 * @exception IOException If an error occurs
184 public Socket (InetAddress address
, int port
,
185 InetAddress localAddr
, int localPort
) throws IOException
187 this(address
, port
, localAddr
, localPort
, true);
191 * Initializes a new instance of <code>Socket</code> and connects to the
192 * hostname and port specified as arguments. If the stream argument is set
193 * to <code>true</code>, then a stream socket is created. If it is
194 * <code>false</code>, a datagram socket is created.
196 * @param host The name of the host to connect to
197 * @param port The port to connect to
198 * @param stream <code>true</code> for a stream socket, <code>false</code>
199 * for a datagram socket
201 * @exception IOException If an error occurs
203 * @deprecated Use the <code>DatagramSocket</code> class to create
204 * datagram oriented sockets.
206 public Socket (String host
, int port
, boolean stream
) throws IOException
208 this(InetAddress
.getByName(host
), port
, null, 0, stream
);
212 * Initializes a new instance of <code>Socket</code> and connects to the
213 * address and port number specified as arguments. If the stream param is
214 * <code>true</code>, a stream socket will be created, otherwise a datagram
217 * @param host The address to connect to
218 * @param port The port number to connect to
219 * @param stream <code>true</code> to create a stream socket,
220 * <code>false</code> to create a datagram socket.
222 * @exception IOException If an error occurs
224 * @deprecated Use the <code>DatagramSocket</code> class to create
225 * datagram oriented sockets.
227 public Socket (InetAddress host
, int port
, boolean stream
) throws IOException
229 this(host
, port
, null, 0, stream
);
233 * This constructor is where the real work takes place. Connect to the
234 * specified address and port. Use default local values if not specified,
235 * otherwise use the local host and port passed in. Create as stream or
236 * datagram based on "stream" argument.
239 * @param raddr The remote address to connect to
240 * @param rport The remote port to connect to
241 * @param laddr The local address to connect to
242 * @param lport The local port to connect to
243 * @param stream true for a stream socket, false for a datagram socket
245 * @exception IOException If an error occurs
247 private Socket(InetAddress raddr
, int rport
, InetAddress laddr
, int lport
,
248 boolean stream
) throws IOException
252 throw new IOException("Cannot initialize Socket implementation");
254 SecurityManager sm
= System
.getSecurityManager();
256 sm
.checkConnect(raddr
.getHostName(), rport
);
260 // FIXME: JCL p. 1586 says if localPort is unspecified, bind to any port,
261 // i.e. '0' and if localAddr is unspecified, use getLocalAddress() as
262 // that default. JDK 1.2 doc infers not to do a bind.
264 impl
.bind(laddr
, lport
);
267 impl
.connect(raddr
, rport
);
271 * Binds the socket to the givent local address/port
273 * @param bindpoint The address/port to bind to
275 * @exception If an error occurs
279 public void bind (SocketAddress bindpoint
) throws IOException
281 if ( !(bindpoint
instanceof InetSocketAddress
))
282 throw new IllegalArgumentException ();
284 InetSocketAddress tmp
= (InetSocketAddress
) bindpoint
;
285 impl
.bind (tmp
.getAddress(), tmp
.getPort());
289 * Connects the socket with a remote address.
291 * @param endpoint The address to connect to
293 * @exception IOException If an error occurs
297 public void connect (SocketAddress endpoint
)
300 impl
.connect (endpoint
, 0);
304 * Connects the socket with a remote address. A timeout of zero is
305 * interpreted as an infinite timeout. The connection will then block
306 * until established or an error occurs.
308 * @param endpoint The address to connect to
310 * @exception IOException If an error occurs
314 public void connect (SocketAddress endpoint
, int timeout
)
317 impl
.connect (endpoint
, timeout
);
321 * Returns the address of the remote end of the socket. If this socket
322 * is not connected, then <code>null</code> is returned.
324 * @return The remote address this socket is connected to
326 public InetAddress
getInetAddress ()
329 return impl
.getInetAddress();
335 * Returns the local address to which this socket is bound. If this socket
336 * is not connected, then <code>null</code> is returned.
338 * @return The local address
340 public InetAddress
getLocalAddress ()
345 InetAddress addr
= null;
348 addr
= (InetAddress
)impl
.getOption(SocketOptions
.SO_BINDADDR
);
350 catch(SocketException e
)
352 // (hopefully) shouldn't happen
353 // throw new java.lang.InternalError
354 // ("Error in PlainSocketImpl.getOption");
358 // FIXME: According to libgcj, checkConnect() is supposed to be called
359 // before performing this operation. Problems: 1) We don't have the
360 // addr until after we do it, so we do a post check. 2). The docs I
361 // see don't require this in the Socket case, only DatagramSocket, but
362 // we'll assume they mean both.
363 SecurityManager sm
= System
.getSecurityManager();
365 sm
.checkConnect(addr
.getHostName(), getLocalPort());
371 * Returns the port number of the remote end of the socket connection. If
372 * this socket is not connected, then -1 is returned.
374 * @return The remote port this socket is connected to
376 public int getPort ()
379 return impl
.getPort();
385 * Returns the local port number to which this socket is bound. If this
386 * socket is not connected, then -1 is returned.
388 * @return The local port
390 public int getLocalPort ()
393 return impl
.getLocalPort();
399 * Returns an InputStream for reading from this socket.
401 * @return The InputStream object
403 * @exception IOException If an error occurs or Socket is not connected
405 public InputStream
getInputStream () throws IOException
408 return(impl
.getInputStream());
410 throw new IOException("Not connected");
414 * Returns an OutputStream for writing to this socket.
416 * @return The OutputStream object
418 * @exception IOException If an error occurs or Socket is not connected
420 public OutputStream
getOutputStream () throws IOException
423 return impl
.getOutputStream();
425 throw new IOException("Not connected");
429 * Sets the TCP_NODELAY option on the socket.
431 * @param on true to enable, false to disable
433 * @exception SocketException If an error occurs or Socket is not connected
435 public void setTcpNoDelay (boolean on
) throws SocketException
438 throw new SocketException("Not connected");
440 impl
.setOption(SocketOptions
.TCP_NODELAY
, new Boolean(on
));
444 * Tests whether or not the TCP_NODELAY option is set on the socket.
445 * Returns true if enabled, false if disabled. When on it disables the
446 * Nagle algorithm which means that packets are always send immediatly and
447 * never merged together to reduce network trafic.
449 * @return Whether or not TCP_NODELAY is set
451 * @exception SocketException If an error occurs or Socket not connected
453 public boolean getTcpNoDelay() throws SocketException
456 throw new SocketException("Not connected");
458 Object on
= impl
.getOption(SocketOptions
.TCP_NODELAY
);
460 if (on
instanceof Boolean
)
461 return(((Boolean
)on
).booleanValue());
463 throw new SocketException("Internal Error");
467 * Sets the value of the SO_LINGER option on the socket. If the
468 * SO_LINGER option is set on a socket and there is still data waiting to
469 * be sent when the socket is closed, then the close operation will block
470 * until either that data is delivered or until the timeout period
471 * expires. The linger interval is specified in hundreths of a second
472 * (platform specific?)
474 * @param on true to enable SO_LINGER, false to disable
475 * @param linger The SO_LINGER timeout in hundreths of a second or -1 if
478 * @exception SocketException If an error occurs or Socket not connected
480 public void setSoLinger(boolean on
, int linger
) throws SocketException
483 throw new SocketException("No socket created");
488 throw new IllegalArgumentException("SO_LINGER must be >= 0");
493 impl
.setOption(SocketOptions
.SO_LINGER
, new Integer(linger
));
497 impl
.setOption(SocketOptions
.SO_LINGER
, new Boolean(false));
502 * Returns the value of the SO_LINGER option on the socket. If the
503 * SO_LINGER option is set on a socket and there is still data waiting to
504 * be sent when the socket is closed, then the close operation will block
505 * until either that data is delivered or until the timeout period
506 * expires. This method either returns the timeouts (in hundredths of
507 * of a second (platform specific?)) if SO_LINGER is set, or -1 if
508 * SO_LINGER is not set.
510 * @return The SO_LINGER timeout in hundreths of a second or -1
511 * if SO_LINGER not set
513 * @exception SocketException If an error occurs or Socket is not connected
515 public int getSoLinger() throws SocketException
518 throw new SocketException("Not connected");
520 Object linger
= impl
.getOption(SocketOptions
.SO_LINGER
);
521 if (linger
instanceof Integer
)
522 return(((Integer
)linger
).intValue());
528 * Enables/disables the SO_OOBINLINE option
530 * @param on True if SO_OOBLINE should be enabled
532 * @exception SocketException If an error occurs
536 public void setOOBInline (boolean on
) throws SocketException
539 throw new SocketException("Not connected");
541 impl
.setOption(SocketOptions
.SO_OOBINLINE
, new Boolean(on
));
545 * Returns the current setting of the SO_OOBINLINE option for this socket
547 * @exception SocketException If an error occurs
551 public boolean getOOBInline () throws SocketException
554 throw new SocketException("Not connected");
556 Object buf
= impl
.getOption(SocketOptions
.SO_OOBINLINE
);
558 if (buf
instanceof Boolean
)
559 return(((Boolean
)buf
).booleanValue());
561 throw new SocketException("Internal Error: Unexpected type");
565 * Sets the value of the SO_TIMEOUT option on the socket. If this value
566 * is set, and an read/write is performed that does not complete within
567 * the timeout period, a short count is returned (or an EWOULDBLOCK signal
568 * would be sent in Unix if no data had been read). A value of 0 for
569 * this option implies that there is no timeout (ie, operations will
570 * block forever). On systems that have separate read and write timeout
571 * values, this method returns the read timeout. This
572 * value is in thousandths of a second (****????*****)
574 * @param timeout The length of the timeout in thousandth's of a second or
577 * @exception SocketException If an error occurs or Socket not connected
579 public synchronized void setSoTimeout (int timeout
) throws SocketException
582 throw new SocketException("Not connected");
585 throw new IllegalArgumentException("SO_TIMEOUT value must be >= 0");
587 impl
.setOption(SocketOptions
.SO_TIMEOUT
, new Integer(timeout
));
591 * Returns the value of the SO_TIMEOUT option on the socket. If this value
592 * is set, and an read/write is performed that does not complete within
593 * the timeout period, a short count is returned (or an EWOULDBLOCK signal
594 * would be sent in Unix if no data had been read). A value of 0 for
595 * this option implies that there is no timeout (ie, operations will
596 * block forever). On systems that have separate read and write timeout
597 * values, this method returns the read timeout. This
598 * value is in thousandths of a second (implementation specific?).
600 * @return The length of the timeout in thousandth's of a second or 0
603 * @exception SocketException If an error occurs or Socket not connected
605 public synchronized int getSoTimeout () throws SocketException
608 throw new SocketException("Not connected");
610 Object timeout
= impl
.getOption(SocketOptions
.SO_TIMEOUT
);
611 if (timeout
instanceof Integer
)
612 return(((Integer
)timeout
).intValue());
618 * This method sets the value for the system level socket option
619 * SO_SNDBUF to the specified value. Note that valid values for this
620 * option are specific to a given operating system.
622 * @param size The new send buffer size.
624 * @exception SocketException If an error occurs or Socket not connected
628 public void setSendBufferSize (int size
) throws SocketException
631 throw new SocketException("Not connected");
634 throw new IllegalArgumentException("SO_SNDBUF value must be > 0");
636 impl
.setOption(SocketOptions
.SO_SNDBUF
, new Integer(size
));
640 * This method returns the value of the system level socket option
641 * SO_SNDBUF, which is used by the operating system to tune buffer
642 * sizes for data transfers.
644 * @return The send buffer size.
646 * @exception SocketException If an error occurs or socket not connected
650 public int getSendBufferSize () throws SocketException
653 throw new SocketException("Not connected");
655 Object buf
= impl
.getOption(SocketOptions
.SO_SNDBUF
);
657 if (buf
instanceof Integer
)
658 return(((Integer
)buf
).intValue());
660 throw new SocketException("Internal Error: Unexpected type");
664 * This method sets the value for the system level socket option
665 * SO_RCVBUF to the specified value. Note that valid values for this
666 * option are specific to a given operating system.
668 * @param size The new receive buffer size.
670 * @exception SocketException If an error occurs or Socket is not connected
674 public void setReceiveBufferSize (int size
) throws SocketException
677 throw new SocketException("Not connected");
680 throw new IllegalArgumentException("SO_RCVBUF value must be > 0");
682 impl
.setOption(SocketOptions
.SO_RCVBUF
, new Integer(size
));
686 * This method returns the value of the system level socket option
687 * SO_RCVBUF, which is used by the operating system to tune buffer
688 * sizes for data transfers.
690 * @return The receive buffer size.
692 * @exception SocketException If an error occurs or Socket is not connected
696 public int getReceiveBufferSize () throws SocketException
699 throw new SocketException("Not connected");
701 Object buf
= impl
.getOption(SocketOptions
.SO_RCVBUF
);
703 if (buf
instanceof Integer
)
704 return(((Integer
)buf
).intValue());
706 throw new SocketException("Internal Error: Unexpected type");
710 * This method sets the value for the socket level socket option
713 * @param on True if SO_KEEPALIVE should be enabled
715 * @exception SocketException If an error occurs or Socket is not connected
719 public void setKeepAlive (boolean on
) throws SocketException
722 throw new SocketException("Not connected");
724 impl
.setOption(SocketOptions
.SO_KEEPALIVE
, new Boolean(on
));
728 * This method returns the value of the socket level socket option
731 * @return The setting
733 * @exception SocketException If an error occurs or Socket is not connected
737 public boolean getKeepAlive () throws SocketException
740 throw new SocketException("Not connected");
742 Object buf
= impl
.getOption(SocketOptions
.SO_KEEPALIVE
);
744 if (buf
instanceof Boolean
)
745 return(((Boolean
)buf
).booleanValue());
747 throw new SocketException("Internal Error: Unexpected type");
753 * @exception IOException If an error occurs
755 public synchronized void close () throws IOException
762 * Converts this <code>Socket</code> to a <code>String</code>.
764 * @return The <code>String</code> representation of this <code>Socket</code>
766 public String
toString ()
768 return("Socket " + impl
);
774 * Sets the <code>SocketImplFactory</code>. This may be done only once per
775 * virtual machine. Subsequent attempts will generate a
776 * <code>SocketException</code>. Note that a <code>SecurityManager</code>
777 * check is made prior to setting the factory. If
778 * insufficient privileges exist to set the factory, then an
779 * <code>IOException</code> will be thrown.
781 * @exception SecurityException If the <code>SecurityManager</code> does
782 * not allow this operation.
783 * @exception SocketException If the SocketImplFactory is already defined
784 * @exception IOException If any other error occurs
786 public static synchronized void setSocketImplFactory (SocketImplFactory fac
)
789 // See if already set
791 throw new SocketException("SocketImplFactory already defined");
794 SecurityManager sm
= System
.getSecurityManager();
796 sm
.checkSetFactory();
802 * Closes the input side of the socket stream.
804 * @exception IOException If an error occurs.
806 public void shutdownInput() throws IOException
809 impl
.shutdownInput();
813 * Closes the output side of the socket stream.
815 * @exception IOException If an error occurs.
817 public void shutdownOutput() throws IOException
820 impl
.shutdownOutput();