Socket.java 32 KB

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