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.
91 impl
= factory
.createSocketImpl();
93 impl
= new PlainSocketImpl();
97 * Initializes a new instance of <code>Socket</code> object without
98 * connecting to a remote host. This is useful for subclasses of socket
99 * that might want this behavior.
101 * Additionally, this socket will be created using the supplied
102 * implementation class instead the default class or one returned by a
103 * factory. This value can be <code>null</code>, but if it is, all instance
104 * methods in <code>Socket</code> should be overridden because most of them
105 * rely on this value being populated.
107 * @param impl The <code>SocketImpl</code> to use for this
108 * <code>Socket</code>
110 * @exception SocketException If an error occurs
112 protected Socket (SocketImpl impl
) throws SocketException
118 * Initializes a new instance of <code>Socket</code> and connects to the
119 * hostname and port specified as arguments.
121 * @param host The name of the host to connect to
122 * @param port The port number to connect to
124 * @exception UnknownHostException If the hostname cannot be resolved to a
126 * @exception IOException If an error occurs
128 public Socket (String host
, int port
)
129 throws UnknownHostException
, IOException
131 this(InetAddress
.getByName(host
), port
, null, 0, true);
135 * Initializes a new instance of <code>Socket</code> and connects to the
136 * address and port number specified as arguments.
138 * @param address The address to connect to
139 * @param port The port number to connect to
141 * @exception IOException If an error occurs
143 public Socket (InetAddress address
, int port
)
146 this(address
, port
, null, 0, true);
150 * Initializes a new instance of <code>Socket</code> that connects to the
151 * named host on the specified port and binds to the specified local address
154 * @param host The name of the remote host to connect to.
155 * @param port The remote port to connect to.
156 * @param loadAddr The local address to bind to.
157 * @param localPort The local port to bind to.
159 * @exception SecurityException If the <code>SecurityManager</code>
160 * exists and does not allow a connection to the specified host/port or
161 * binding to the specified local host/port.
162 * @exception IOException If a connection error occurs.
164 public Socket (String host
, int port
,
165 InetAddress localAddr
, int localPort
) throws IOException
167 this(InetAddress
.getByName(host
), port
, localAddr
, localPort
, true);
171 * Initializes a new instance of <code>Socket</code> and connects to the
172 * address and port number specified as arguments, plus binds to the
173 * specified local address and port.
175 * @param address The remote address to connect to
176 * @param port The remote port to connect to
177 * @param localAddr The local address to connect to
178 * @param localPort The local port to connect to
180 * @exception IOException If an error occurs
182 public Socket (InetAddress address
, int port
,
183 InetAddress localAddr
, int localPort
) throws IOException
185 this(address
, port
, localAddr
, localPort
, true);
189 * Initializes a new instance of <code>Socket</code> and connects to the
190 * hostname and port specified as arguments. If the stream argument is set
191 * to <code>true</code>, then a stream socket is created. If it is
192 * <code>false</code>, a datagram socket is created.
194 * @param host The name of the host to connect to
195 * @param port The port to connect to
196 * @param stream <code>true</code> for a stream socket, <code>false</code>
197 * for a datagram socket
199 * @exception IOException If an error occurs
201 * @deprecated Use the <code>DatagramSocket</code> class to create
202 * datagram oriented sockets.
204 public Socket (String host
, int port
, boolean stream
) throws IOException
206 this(InetAddress
.getByName(host
), port
, null, 0, stream
);
210 * Initializes a new instance of <code>Socket</code> and connects to the
211 * address and port number specified as arguments. If the stream param is
212 * <code>true</code>, a stream socket will be created, otherwise a datagram
215 * @param host The address to connect to
216 * @param port The port number to connect to
217 * @param stream <code>true</code> to create a stream socket,
218 * <code>false</code> to create a datagram socket.
220 * @exception IOException If an error occurs
222 * @deprecated Use the <code>DatagramSocket</code> class to create
223 * datagram oriented sockets.
225 public Socket (InetAddress host
, int port
, boolean stream
) throws IOException
227 this(host
, port
, null, 0, stream
);
231 * This constructor is where the real work takes place. Connect to the
232 * specified address and port. Use default local values if not specified,
233 * otherwise use the local host and port passed in. Create as stream or
234 * datagram based on "stream" argument.
237 * @param raddr The remote address to connect to
238 * @param rport The remote port to connect to
239 * @param laddr The local address to connect to
240 * @param lport The local port to connect to
241 * @param stream true for a stream socket, false for a datagram socket
243 * @exception IOException If an error occurs
245 private Socket(InetAddress raddr
, int rport
, InetAddress laddr
, int lport
,
246 boolean stream
) throws IOException
250 throw new IOException("Cannot initialize Socket implementation");
252 SecurityManager sm
= System
.getSecurityManager();
254 sm
.checkConnect(raddr
.getHostName(), rport
);
258 // FIXME: JCL p. 1586 says if localPort is unspecified, bind to any port,
259 // i.e. '0' and if localAddr is unspecified, use getLocalAddress() as
260 // that default. JDK 1.2 doc infers not to do a bind.
262 impl
.bind(laddr
, lport
);
265 impl
.connect(raddr
, rport
);
269 * Returns the address of the remote end of the socket. If this socket
270 * is not connected, then <code>null</code> is returned.
272 * @return The remote address this socket is connected to
274 public InetAddress
getInetAddress ()
277 return impl
.getInetAddress();
283 * Returns the local address to which this socket is bound. If this socket
284 * is not connected, then <code>null</code> is returned.
286 * @return The local address
288 public InetAddress
getLocalAddress ()
293 InetAddress addr
= null;
296 addr
= (InetAddress
)impl
.getOption(SocketOptions
.SO_BINDADDR
);
298 catch(SocketException e
)
300 // (hopefully) shouldn't happen
301 // throw new java.lang.InternalError
302 // ("Error in PlainSocketImpl.getOption");
306 // FIXME: According to libgcj, checkConnect() is supposed to be called
307 // before performing this operation. Problems: 1) We don't have the
308 // addr until after we do it, so we do a post check. 2). The docs I
309 // see don't require this in the Socket case, only DatagramSocket, but
310 // we'll assume they mean both.
311 SecurityManager sm
= System
.getSecurityManager();
313 sm
.checkConnect(addr
.getHostName(), getLocalPort());
319 * Returns the port number of the remote end of the socket connection. If
320 * this socket is not connected, then -1 is returned.
322 * @return The remote port this socket is connected to
324 public int getPort ()
327 return impl
.getPort();
333 * Returns the local port number to which this socket is bound. If this
334 * socket is not connected, then -1 is returned.
336 * @return The local port
338 public int getLocalPort ()
341 return impl
.getLocalPort();
347 * Returns an InputStream for reading from this socket.
349 * @return The InputStream object
351 * @exception IOException If an error occurs or Socket is not connected
353 public InputStream
getInputStream () throws IOException
356 return(impl
.getInputStream());
358 throw new IOException("Not connected");
362 * Returns an OutputStream for writing to this socket.
364 * @return The OutputStream object
366 * @exception IOException If an error occurs or Socket is not connected
368 public OutputStream
getOutputStream () throws IOException
371 return impl
.getOutputStream();
373 throw new IOException("Not connected");
377 * Sets the TCP_NODELAY option on the socket.
379 * @param on true to enable, false to disable
381 * @exception SocketException If an error occurs or Socket is not connected
383 public void setTcpNoDelay (boolean on
) throws SocketException
386 throw new SocketException("Not connected");
388 impl
.setOption(SocketOptions
.TCP_NODELAY
, new Boolean(on
));
392 * Tests whether or not the TCP_NODELAY option is set on the socket.
393 * Returns true if enabled, false if disabled. When on it disables the
394 * Nagle algorithm which means that packets are always send immediatly and
395 * never merged together to reduce network trafic.
397 * @return Whether or not TCP_NODELAY is set
399 * @exception SocketException If an error occurs or Socket not connected
401 public boolean getTcpNoDelay() throws SocketException
404 throw new SocketException("Not connected");
406 Object on
= impl
.getOption(SocketOptions
.TCP_NODELAY
);
408 if (on
instanceof Boolean
)
409 return(((Boolean
)on
).booleanValue());
411 throw new SocketException("Internal Error");
415 * Sets the value of the SO_LINGER option on the socket. If the
416 * SO_LINGER option is set on a socket and there is still data waiting to
417 * be sent when the socket is closed, then the close operation will block
418 * until either that data is delivered or until the timeout period
419 * expires. The linger interval is specified in hundreths of a second
420 * (platform specific?)
422 * @param on true to enable SO_LINGER, false to disable
423 * @param linger The SO_LINGER timeout in hundreths of a second or -1 if
426 * @exception SocketException If an error occurs or Socket not connected
428 public void setSoLinger(boolean on
, int linger
) throws SocketException
431 throw new SocketException("No socket created");
436 throw new IllegalArgumentException("SO_LINGER must be >= 0");
441 impl
.setOption(SocketOptions
.SO_LINGER
, new Integer(linger
));
445 impl
.setOption(SocketOptions
.SO_LINGER
, new Boolean(false));
450 * Returns the value of the SO_LINGER option on the socket. If the
451 * SO_LINGER option is set on a socket and there is still data waiting to
452 * be sent when the socket is closed, then the close operation will block
453 * until either that data is delivered or until the timeout period
454 * expires. This method either returns the timeouts (in hundredths of
455 * of a second (platform specific?)) if SO_LINGER is set, or -1 if
456 * SO_LINGER is not set.
458 * @return The SO_LINGER timeout in hundreths of a second or -1
459 * if SO_LINGER not set
461 * @exception SocketException If an error occurs or Socket is not connected
463 public int getSoLinger() throws SocketException
466 throw new SocketException("Not connected");
468 Object linger
= impl
.getOption(SocketOptions
.SO_LINGER
);
469 if (linger
instanceof Integer
)
470 return(((Integer
)linger
).intValue());
476 * Sets the value of the SO_TIMEOUT option on the socket. If this value
477 * is set, and an read/write is performed that does not complete within
478 * the timeout period, a short count is returned (or an EWOULDBLOCK signal
479 * would be sent in Unix if no data had been read). A value of 0 for
480 * this option implies that there is no timeout (ie, operations will
481 * block forever). On systems that have separate read and write timeout
482 * values, this method returns the read timeout. This
483 * value is in thousandths of a second (****????*****)
485 * @param timeout The length of the timeout in thousandth's of a second or
488 * @exception SocketException If an error occurs or Socket not connected
490 public synchronized void setSoTimeout (int timeout
) throws SocketException
493 throw new SocketException("Not connected");
496 throw new IllegalArgumentException("SO_TIMEOUT value must be >= 0");
498 impl
.setOption(SocketOptions
.SO_TIMEOUT
, new Integer(timeout
));
502 * Returns the value of the SO_TIMEOUT option on the socket. If this value
503 * is set, and an read/write is performed that does not complete within
504 * the timeout period, a short count is returned (or an EWOULDBLOCK signal
505 * would be sent in Unix if no data had been read). A value of 0 for
506 * this option implies that there is no timeout (ie, operations will
507 * block forever). On systems that have separate read and write timeout
508 * values, this method returns the read timeout. This
509 * value is in thousandths of a second (implementation specific?).
511 * @return The length of the timeout in thousandth's of a second or 0
514 * @exception SocketException If an error occurs or Socket not connected
516 public synchronized int getSoTimeout () throws SocketException
519 throw new SocketException("Not connected");
521 Object timeout
= impl
.getOption(SocketOptions
.SO_TIMEOUT
);
522 if (timeout
instanceof Integer
)
523 return(((Integer
)timeout
).intValue());
529 * This method sets the value for the system level socket option
530 * SO_SNDBUF to the specified value. Note that valid values for this
531 * option are specific to a given operating system.
533 * @param size The new send buffer size.
535 * @exception SocketException If an error occurs or Socket not connected
539 public void setSendBufferSize (int size
) throws SocketException
542 throw new SocketException("Not connected");
545 throw new IllegalArgumentException("SO_SNDBUF value must be > 0");
547 impl
.setOption(SocketOptions
.SO_SNDBUF
, new Integer(size
));
551 * This method returns the value of the system level socket option
552 * SO_SNDBUF, which is used by the operating system to tune buffer
553 * sizes for data transfers.
555 * @return The send buffer size.
557 * @exception SocketException If an error occurs or socket not connected
561 public int getSendBufferSize () throws SocketException
564 throw new SocketException("Not connected");
566 Object buf
= impl
.getOption(SocketOptions
.SO_SNDBUF
);
568 if (buf
instanceof Integer
)
569 return(((Integer
)buf
).intValue());
571 throw new SocketException("Internal Error: Unexpected type");
575 * This method sets the value for the system level socket option
576 * SO_RCVBUF to the specified value. Note that valid values for this
577 * option are specific to a given operating system.
579 * @param size The new receive buffer size.
581 * @exception SocketException If an error occurs or Socket is not connected
585 public void setReceiveBufferSize (int size
) throws SocketException
588 throw new SocketException("Not connected");
591 throw new IllegalArgumentException("SO_RCVBUF value must be > 0");
593 impl
.setOption(SocketOptions
.SO_RCVBUF
, new Integer(size
));
597 * This method returns the value of the system level socket option
598 * SO_RCVBUF, which is used by the operating system to tune buffer
599 * sizes for data transfers.
601 * @return The receive buffer size.
603 * @exception SocketException If an error occurs or Socket is not connected
607 public int getReceiveBufferSize () throws SocketException
610 throw new SocketException("Not connected");
612 Object buf
= impl
.getOption(SocketOptions
.SO_RCVBUF
);
614 if (buf
instanceof Integer
)
615 return(((Integer
)buf
).intValue());
617 throw new SocketException("Internal Error: Unexpected type");
621 * This method sets the value for the socket level socket option
624 * @param on True if SO_KEEPALIVE should be enabled
626 * @exception SocketException If an error occurs or Socket is not connected
630 public void setKeepAlive (boolean on
) throws SocketException
633 throw new SocketException("Not connected");
635 impl
.setOption(SocketOptions
.SO_RCVBUF
, new Boolean(on
));
639 * This method returns the value of the socket level socket option
642 * @return The setting
644 * @exception SocketException If an error occurs or Socket is not connected
648 public boolean getKeepAlive () throws SocketException
651 throw new SocketException("Not connected");
653 Object buf
= impl
.getOption(SocketOptions
.SO_RCVBUF
);
655 if (buf
instanceof Boolean
)
656 return(((Boolean
)buf
).booleanValue());
658 throw new SocketException("Internal Error: Unexpected type");
664 * @exception IOException If an error occurs
666 public synchronized void close () throws IOException
673 * Converts this <code>Socket</code> to a <code>String</code>.
675 * @return The <code>String</code> representation of this <code>Socket</code>
677 public String
toString ()
679 return("Socket " + impl
);
685 * Sets the <code>SocketImplFactory</code>. This may be done only once per
686 * virtual machine. Subsequent attempts will generate a
687 * <code>SocketException</code>. Note that a <code>SecurityManager</code>
688 * check is made prior to setting the factory. If
689 * insufficient privileges exist to set the factory, then an
690 * <code>IOException</code> will be thrown.
692 * @exception SecurityException If the <code>SecurityManager</code> does
693 * not allow this operation.
694 * @exception SocketException If the SocketImplFactory is already defined
695 * @exception IOException If any other error occurs
697 public static synchronized void setSocketImplFactory (SocketImplFactory fac
)
700 // See if already set
702 throw new SocketException("SocketImplFactory already defined");
705 SecurityManager sm
= System
.getSecurityManager();
707 sm
.checkSetFactory();
713 * Closes the input side of the socket stream.
715 * @exception IOException If an error occurs.
717 public void shutdownInput() throws IOException
720 impl
.shutdownInput();
724 * Closes the output side of the socket stream.
726 * @exception IOException If an error occurs.
728 public void shutdownOutput() throws IOException
731 impl
.shutdownOutput();