PageRenderTime 28ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/src/share/classes/java/net/Socket.java

https://bitbucket.org/bjzrccf/jdk6-jdk-mips
Java | 1580 lines | 538 code | 80 blank | 962 comment | 128 complexity | 8c3930630ea0569ff8b58a5001ee7c36 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, LGPL-3.0
  1. /*
  2. * Copyright 1995-2007 Sun Microsystems, Inc. All Rights Reserved.
  3. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4. *
  5. * This code is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License version 2 only, as
  7. * published by the Free Software Foundation. Sun designates this
  8. * particular file as subject to the "Classpath" exception as provided
  9. * by Sun in the LICENSE file that accompanied this code.
  10. *
  11. * This code is distributed in the hope that it will be useful, but WITHOUT
  12. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  14. * version 2 for more details (a copy is included in the LICENSE file that
  15. * accompanied this code).
  16. *
  17. * You should have received a copy of the GNU General Public License version
  18. * 2 along with this work; if not, write to the Free Software Foundation,
  19. * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20. *
  21. * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  22. * CA 95054 USA or visit www.sun.com if you need additional information or
  23. * have any questions.
  24. */
  25. package java.net;
  26. import java.io.InputStream;
  27. import java.io.OutputStream;
  28. import java.io.IOException;
  29. import java.io.InterruptedIOException;
  30. import java.nio.channels.SocketChannel;
  31. import java.security.AccessController;
  32. import java.security.PrivilegedExceptionAction;
  33. import java.security.PrivilegedAction;
  34. /**
  35. * This class implements client sockets (also called just
  36. * "sockets"). A socket is an endpoint for communication
  37. * between two machines.
  38. * <p>
  39. * The actual work of the socket is performed by an instance of the
  40. * <code>SocketImpl</code> class. An application, by changing
  41. * the socket factory that creates the socket implementation,
  42. * can configure itself to create sockets appropriate to the local
  43. * firewall.
  44. *
  45. * @author unascribed
  46. * @see java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory)
  47. * @see java.net.SocketImpl
  48. * @see java.nio.channels.SocketChannel
  49. * @since JDK1.0
  50. */
  51. public
  52. class Socket {
  53. /**
  54. * Various states of this socket.
  55. */
  56. private boolean created = false;
  57. private boolean bound = false;
  58. private boolean connected = false;
  59. private boolean closed = false;
  60. private Object closeLock = new Object();
  61. private boolean shutIn = false;
  62. private boolean shutOut = false;
  63. /**
  64. * The implementation of this Socket.
  65. */
  66. SocketImpl impl;
  67. /**
  68. * Are we using an older SocketImpl?
  69. */
  70. private boolean oldImpl = false;
  71. /**
  72. * Creates an unconnected socket, with the
  73. * system-default type of SocketImpl.
  74. *
  75. * @since JDK1.1
  76. * @revised 1.4
  77. */
  78. public Socket() {
  79. setImpl();
  80. }
  81. /**
  82. * Creates an unconnected socket, specifying the type of proxy, if any,
  83. * that should be used regardless of any other settings.
  84. * <P>
  85. * If there is a security manager, its <code>checkConnect</code> method
  86. * is called with the proxy host address and port number
  87. * as its arguments. This could result in a SecurityException.
  88. * <P>
  89. * Examples:
  90. * <UL> <LI><code>Socket s = new Socket(Proxy.NO_PROXY);</code> will create
  91. * a plain socket ignoring any other proxy configuration.</LI>
  92. * <LI><code>Socket s = new Socket(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("socks.mydom.com", 1080)));</code>
  93. * will create a socket connecting through the specified SOCKS proxy
  94. * server.</LI>
  95. * </UL>
  96. *
  97. * @param proxy a {@link java.net.Proxy Proxy} object specifying what kind
  98. * of proxying should be used.
  99. * @throws IllegalArgumentException if the proxy is of an invalid type
  100. * or <code>null</code>.
  101. * @throws SecurityException if a security manager is present and
  102. * permission to connect to the proxy is
  103. * denied.
  104. * @see java.net.ProxySelector
  105. * @see java.net.Proxy
  106. *
  107. * @since 1.5
  108. */
  109. public Socket(Proxy proxy) {
  110. // Create a copy of Proxy as a security measure
  111. if (proxy == null) {
  112. throw new IllegalArgumentException("Invalid Proxy");
  113. }
  114. Proxy p = proxy == Proxy.NO_PROXY ? Proxy.NO_PROXY : sun.net.ApplicationProxy.create(proxy);
  115. if (p.type() == Proxy.Type.SOCKS) {
  116. SecurityManager security = System.getSecurityManager();
  117. InetSocketAddress epoint = (InetSocketAddress) p.address();
  118. if (security != null) {
  119. if (epoint.isUnresolved())
  120. epoint = new InetSocketAddress(epoint.getHostName(), epoint.getPort());
  121. if (epoint.isUnresolved())
  122. security.checkConnect(epoint.getHostName(),
  123. epoint.getPort());
  124. else
  125. security.checkConnect(epoint.getAddress().getHostAddress(),
  126. epoint.getPort());
  127. }
  128. impl = new SocksSocketImpl(p);
  129. impl.setSocket(this);
  130. } else {
  131. if (p == Proxy.NO_PROXY) {
  132. if (factory == null) {
  133. impl = new PlainSocketImpl();
  134. impl.setSocket(this);
  135. } else
  136. setImpl();
  137. } else
  138. throw new IllegalArgumentException("Invalid Proxy");
  139. }
  140. }
  141. /**
  142. * Creates an unconnected Socket with a user-specified
  143. * SocketImpl.
  144. * <P>
  145. * @param impl an instance of a <B>SocketImpl</B>
  146. * the subclass wishes to use on the Socket.
  147. *
  148. * @exception SocketException if there is an error in the underlying protocol,
  149. * such as a TCP error.
  150. * @since JDK1.1
  151. */
  152. protected Socket(SocketImpl impl) throws SocketException {
  153. this.impl = impl;
  154. if (impl != null) {
  155. checkOldImpl();
  156. this.impl.setSocket(this);
  157. }
  158. }
  159. /**
  160. * Creates a stream socket and connects it to the specified port
  161. * number on the named host.
  162. * <p>
  163. * If the specified host is <tt>null</tt> it is the equivalent of
  164. * specifying the address as <tt>{@link java.net.InetAddress#getByName InetAddress.getByName}(null)</tt>.
  165. * In other words, it is equivalent to specifying an address of the
  166. * loopback interface. </p>
  167. * <p>
  168. * If the application has specified a server socket factory, that
  169. * factory's <code>createSocketImpl</code> method is called to create
  170. * the actual socket implementation. Otherwise a "plain" socket is created.
  171. * <p>
  172. * If there is a security manager, its
  173. * <code>checkConnect</code> method is called
  174. * with the host address and <code>port</code>
  175. * as its arguments. This could result in a SecurityException.
  176. *
  177. * @param host the host name, or <code>null</code> for the loopback address.
  178. * @param port the port number.
  179. *
  180. * @exception UnknownHostException if the IP address of
  181. * the host could not be determined.
  182. *
  183. * @exception IOException if an I/O error occurs when creating the socket.
  184. * @exception SecurityException if a security manager exists and its
  185. * <code>checkConnect</code> method doesn't allow the operation.
  186. * @see java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory)
  187. * @see java.net.SocketImpl
  188. * @see java.net.SocketImplFactory#createSocketImpl()
  189. * @see SecurityManager#checkConnect
  190. */
  191. public Socket(String host, int port)
  192. throws UnknownHostException, IOException
  193. {
  194. this(host != null ? new InetSocketAddress(host, port) :
  195. new InetSocketAddress(InetAddress.getByName(null), port),
  196. (SocketAddress) null, true);
  197. }
  198. /**
  199. * Creates a stream socket and connects it to the specified port
  200. * number at the specified IP address.
  201. * <p>
  202. * If the application has specified a socket factory, that factory's
  203. * <code>createSocketImpl</code> method is called to create the
  204. * actual socket implementation. Otherwise a "plain" socket is created.
  205. * <p>
  206. * If there is a security manager, its
  207. * <code>checkConnect</code> method is called
  208. * with the host address and <code>port</code>
  209. * as its arguments. This could result in a SecurityException.
  210. *
  211. * @param address the IP address.
  212. * @param port the port number.
  213. * @exception IOException if an I/O error occurs when creating the socket.
  214. * @exception SecurityException if a security manager exists and its
  215. * <code>checkConnect</code> method doesn't allow the operation.
  216. * @see java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory)
  217. * @see java.net.SocketImpl
  218. * @see java.net.SocketImplFactory#createSocketImpl()
  219. * @see SecurityManager#checkConnect
  220. */
  221. public Socket(InetAddress address, int port) throws IOException {
  222. this(address != null ? new InetSocketAddress(address, port) : null,
  223. (SocketAddress) null, true);
  224. }
  225. /**
  226. * Creates a socket and connects it to the specified remote host on
  227. * the specified remote port. The Socket will also bind() to the local
  228. * address and port supplied.
  229. * <p>
  230. * If the specified host is <tt>null</tt> it is the equivalent of
  231. * specifying the address as <tt>{@link java.net.InetAddress#getByName InetAddress.getByName}(null)</tt>.
  232. * In other words, it is equivalent to specifying an address of the
  233. * loopback interface. </p>
  234. * <p>
  235. * If there is a security manager, its
  236. * <code>checkConnect</code> method is called
  237. * with the host address and <code>port</code>
  238. * as its arguments. This could result in a SecurityException.
  239. *
  240. * @param host the name of the remote host, or <code>null</code> for the loopback address.
  241. * @param port the remote port
  242. * @param localAddr the local address the socket is bound to
  243. * @param localPort the local port the socket is bound to
  244. * @exception IOException if an I/O error occurs when creating the socket.
  245. * @exception SecurityException if a security manager exists and its
  246. * <code>checkConnect</code> method doesn't allow the operation.
  247. * @see SecurityManager#checkConnect
  248. * @since JDK1.1
  249. */
  250. public Socket(String host, int port, InetAddress localAddr,
  251. int localPort) throws IOException {
  252. this(host != null ? new InetSocketAddress(host, port) :
  253. new InetSocketAddress(InetAddress.getByName(null), port),
  254. new InetSocketAddress(localAddr, localPort), true);
  255. }
  256. /**
  257. * Creates a socket and connects it to the specified remote address on
  258. * the specified remote port. The Socket will also bind() to the local
  259. * address and port supplied.
  260. * <p>
  261. * If there is a security manager, its
  262. * <code>checkConnect</code> method is called
  263. * with the host address and <code>port</code>
  264. * as its arguments. This could result in a SecurityException.
  265. *
  266. * @param address the remote address
  267. * @param port the remote port
  268. * @param localAddr the local address the socket is bound to
  269. * @param localPort the local port the socket is bound to
  270. * @exception IOException if an I/O error occurs when creating the socket.
  271. * @exception SecurityException if a security manager exists and its
  272. * <code>checkConnect</code> method doesn't allow the operation.
  273. * @see SecurityManager#checkConnect
  274. * @since JDK1.1
  275. */
  276. public Socket(InetAddress address, int port, InetAddress localAddr,
  277. int localPort) throws IOException {
  278. this(address != null ? new InetSocketAddress(address, port) : null,
  279. new InetSocketAddress(localAddr, localPort), true);
  280. }
  281. /**
  282. * Creates a stream socket and connects it to the specified port
  283. * number on the named host.
  284. * <p>
  285. * If the specified host is <tt>null</tt> it is the equivalent of
  286. * specifying the address as <tt>{@link java.net.InetAddress#getByName InetAddress.getByName}(null)</tt>.
  287. * In other words, it is equivalent to specifying an address of the
  288. * loopback interface. </p>
  289. * <p>
  290. * If the stream argument is <code>true</code>, this creates a
  291. * stream socket. If the stream argument is <code>false</code>, it
  292. * creates a datagram socket.
  293. * <p>
  294. * If the application has specified a server socket factory, that
  295. * factory's <code>createSocketImpl</code> method is called to create
  296. * the actual socket implementation. Otherwise a "plain" socket is created.
  297. * <p>
  298. * If there is a security manager, its
  299. * <code>checkConnect</code> method is called
  300. * with the host address and <code>port</code>
  301. * as its arguments. This could result in a SecurityException.
  302. * <p>
  303. * If a UDP socket is used, TCP/IP related socket options will not apply.
  304. *
  305. * @param host the host name, or <code>null</code> for the loopback address.
  306. * @param port the port number.
  307. * @param stream a <code>boolean</code> indicating whether this is
  308. * a stream socket or a datagram socket.
  309. * @exception IOException if an I/O error occurs when creating the socket.
  310. * @exception SecurityException if a security manager exists and its
  311. * <code>checkConnect</code> method doesn't allow the operation.
  312. * @see java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory)
  313. * @see java.net.SocketImpl
  314. * @see java.net.SocketImplFactory#createSocketImpl()
  315. * @see SecurityManager#checkConnect
  316. * @deprecated Use DatagramSocket instead for UDP transport.
  317. */
  318. @Deprecated
  319. public Socket(String host, int port, boolean stream) throws IOException {
  320. this(host != null ? new InetSocketAddress(host, port) :
  321. new InetSocketAddress(InetAddress.getByName(null), port),
  322. (SocketAddress) null, stream);
  323. }
  324. /**
  325. * Creates a socket and connects it to the specified port number at
  326. * the specified IP address.
  327. * <p>
  328. * If the stream argument is <code>true</code>, this creates a
  329. * stream socket. If the stream argument is <code>false</code>, it
  330. * creates a datagram socket.
  331. * <p>
  332. * If the application has specified a server socket factory, that
  333. * factory's <code>createSocketImpl</code> method is called to create
  334. * the actual socket implementation. Otherwise a "plain" socket is created.
  335. *
  336. * <p>If there is a security manager, its
  337. * <code>checkConnect</code> method is called
  338. * with <code>host.getHostAddress()</code> and <code>port</code>
  339. * as its arguments. This could result in a SecurityException.
  340. * <p>
  341. * If UDP socket is used, TCP/IP related socket options will not apply.
  342. *
  343. * @param host the IP address.
  344. * @param port the port number.
  345. * @param stream if <code>true</code>, create a stream socket;
  346. * otherwise, create a datagram socket.
  347. * @exception IOException if an I/O error occurs when creating the socket.
  348. * @exception SecurityException if a security manager exists and its
  349. * <code>checkConnect</code> method doesn't allow the operation.
  350. * @see java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory)
  351. * @see java.net.SocketImpl
  352. * @see java.net.SocketImplFactory#createSocketImpl()
  353. * @see SecurityManager#checkConnect
  354. * @deprecated Use DatagramSocket instead for UDP transport.
  355. */
  356. @Deprecated
  357. public Socket(InetAddress host, int port, boolean stream) throws IOException {
  358. this(host != null ? new InetSocketAddress(host, port) : null,
  359. new InetSocketAddress(0), stream);
  360. }
  361. private Socket(SocketAddress address, SocketAddress localAddr,
  362. boolean stream) throws IOException {
  363. setImpl();
  364. // backward compatibility
  365. if (address == null)
  366. throw new NullPointerException();
  367. try {
  368. createImpl(stream);
  369. if (localAddr != null)
  370. bind(localAddr);
  371. if (address != null)
  372. connect(address);
  373. } catch (IOException e) {
  374. close();
  375. throw e;
  376. }
  377. }
  378. /**
  379. * Creates the socket implementation.
  380. *
  381. * @param stream a <code>boolean</code> value : <code>true</code> for a TCP socket,
  382. * <code>false</code> for UDP.
  383. * @throws IOException if creation fails
  384. * @since 1.4
  385. */
  386. void createImpl(boolean stream) throws SocketException {
  387. if (impl == null)
  388. setImpl();
  389. try {
  390. impl.create(stream);
  391. created = true;
  392. } catch (IOException e) {
  393. throw new SocketException(e.getMessage());
  394. }
  395. }
  396. private void checkOldImpl() {
  397. if (impl == null)
  398. return;
  399. // SocketImpl.connect() is a protected method, therefore we need to use
  400. // getDeclaredMethod, therefore we need permission to access the member
  401. oldImpl = AccessController.doPrivileged
  402. (new PrivilegedAction<Boolean>() {
  403. public Boolean run() {
  404. Class[] cl = new Class[2];
  405. cl[0] = SocketAddress.class;
  406. cl[1] = Integer.TYPE;
  407. Class clazz = impl.getClass();
  408. while (true) {
  409. try {
  410. clazz.getDeclaredMethod("connect", cl);
  411. return Boolean.FALSE;
  412. } catch (NoSuchMethodException e) {
  413. clazz = clazz.getSuperclass();
  414. // java.net.SocketImpl class will always have this abstract method.
  415. // If we have not found it by now in the hierarchy then it does not
  416. // exist, we are an old style impl.
  417. if (clazz.equals(java.net.SocketImpl.class)) {
  418. return Boolean.TRUE;
  419. }
  420. }
  421. }
  422. }
  423. });
  424. }
  425. /**
  426. * Sets impl to the system-default type of SocketImpl.
  427. * @since 1.4
  428. */
  429. void setImpl() {
  430. if (factory != null) {
  431. impl = factory.createSocketImpl();
  432. checkOldImpl();
  433. } else {
  434. // No need to do a checkOldImpl() here, we know it's an up to date
  435. // SocketImpl!
  436. impl = new SocksSocketImpl();
  437. }
  438. if (impl != null)
  439. impl.setSocket(this);
  440. }
  441. /**
  442. * Get the <code>SocketImpl</code> attached to this socket, creating
  443. * it if necessary.
  444. *
  445. * @return the <code>SocketImpl</code> attached to that ServerSocket.
  446. * @throws SocketException if creation fails
  447. * @since 1.4
  448. */
  449. SocketImpl getImpl() throws SocketException {
  450. if (!created)
  451. createImpl(true);
  452. return impl;
  453. }
  454. /**
  455. * Connects this socket to the server.
  456. *
  457. * @param endpoint the <code>SocketAddress</code>
  458. * @throws IOException if an error occurs during the connection
  459. * @throws java.nio.channels.IllegalBlockingModeException
  460. * if this socket has an associated channel,
  461. * and the channel is in non-blocking mode
  462. * @throws IllegalArgumentException if endpoint is null or is a
  463. * SocketAddress subclass not supported by this socket
  464. * @since 1.4
  465. * @spec JSR-51
  466. */
  467. public void connect(SocketAddress endpoint) throws IOException {
  468. connect(endpoint, 0);
  469. }
  470. /**
  471. * Connects this socket to the server with a specified timeout value.
  472. * A timeout of zero is interpreted as an infinite timeout. The connection
  473. * will then block until established or an error occurs.
  474. *
  475. * @param endpoint the <code>SocketAddress</code>
  476. * @param timeout the timeout value to be used in milliseconds.
  477. * @throws IOException if an error occurs during the connection
  478. * @throws SocketTimeoutException if timeout expires before connecting
  479. * @throws java.nio.channels.IllegalBlockingModeException
  480. * if this socket has an associated channel,
  481. * and the channel is in non-blocking mode
  482. * @throws IllegalArgumentException if endpoint is null or is a
  483. * SocketAddress subclass not supported by this socket
  484. * @since 1.4
  485. * @spec JSR-51
  486. */
  487. public void connect(SocketAddress endpoint, int timeout) throws IOException {
  488. if (endpoint == null)
  489. throw new IllegalArgumentException("connect: The address can't be null");
  490. if (timeout < 0)
  491. throw new IllegalArgumentException("connect: timeout can't be negative");
  492. if (isClosed())
  493. throw new SocketException("Socket is closed");
  494. if (!oldImpl && isConnected())
  495. throw new SocketException("already connected");
  496. if (!(endpoint instanceof InetSocketAddress))
  497. throw new IllegalArgumentException("Unsupported address type");
  498. InetSocketAddress epoint = (InetSocketAddress) endpoint;
  499. SecurityManager security = System.getSecurityManager();
  500. if (security != null) {
  501. if (epoint.isUnresolved())
  502. security.checkConnect(epoint.getHostName(),
  503. epoint.getPort());
  504. else
  505. security.checkConnect(epoint.getAddress().getHostAddress(),
  506. epoint.getPort());
  507. }
  508. if (!created)
  509. createImpl(true);
  510. if (!oldImpl)
  511. impl.connect(epoint, timeout);
  512. else if (timeout == 0) {
  513. if (epoint.isUnresolved())
  514. impl.connect(epoint.getAddress().getHostName(),
  515. epoint.getPort());
  516. else
  517. impl.connect(epoint.getAddress(), epoint.getPort());
  518. } else
  519. throw new UnsupportedOperationException("SocketImpl.connect(addr, timeout)");
  520. connected = true;
  521. /*
  522. * If the socket was not bound before the connect, it is now because
  523. * the kernel will have picked an ephemeral port & a local address
  524. */
  525. bound = true;
  526. }
  527. /**
  528. * Binds the socket to a local address.
  529. * <P>
  530. * If the address is <code>null</code>, then the system will pick up
  531. * an ephemeral port and a valid local address to bind the socket.
  532. *
  533. * @param bindpoint the <code>SocketAddress</code> to bind to
  534. * @throws IOException if the bind operation fails, or if the socket
  535. * is already bound.
  536. * @throws IllegalArgumentException if bindpoint is a
  537. * SocketAddress subclass not supported by this socket
  538. *
  539. * @since 1.4
  540. * @see #isBound
  541. */
  542. public void bind(SocketAddress bindpoint) throws IOException {
  543. if (isClosed())
  544. throw new SocketException("Socket is closed");
  545. if (!oldImpl && isBound())
  546. throw new SocketException("Already bound");
  547. if (bindpoint != null && (!(bindpoint instanceof InetSocketAddress)))
  548. throw new IllegalArgumentException("Unsupported address type");
  549. InetSocketAddress epoint = (InetSocketAddress) bindpoint;
  550. if (epoint != null && epoint.isUnresolved())
  551. throw new SocketException("Unresolved address");
  552. if (bindpoint == null)
  553. getImpl().bind(InetAddress.anyLocalAddress(), 0);
  554. else
  555. getImpl().bind(epoint.getAddress(),
  556. epoint.getPort());
  557. bound = true;
  558. }
  559. /**
  560. * set the flags after an accept() call.
  561. */
  562. final void postAccept() {
  563. connected = true;
  564. created = true;
  565. bound = true;
  566. }
  567. void setCreated() {
  568. created = true;
  569. }
  570. void setBound() {
  571. bound = true;
  572. }
  573. void setConnected() {
  574. connected = true;
  575. }
  576. /**
  577. * Returns the address to which the socket is connected.
  578. *
  579. * @return the remote IP address to which this socket is connected,
  580. * or <code>null</code> if the socket is not connected.
  581. */
  582. public InetAddress getInetAddress() {
  583. if (!isConnected())
  584. return null;
  585. try {
  586. return getImpl().getInetAddress();
  587. } catch (SocketException e) {
  588. }
  589. return null;
  590. }
  591. /**
  592. * Gets the local address to which the socket is bound.
  593. *
  594. * @return the local address to which the socket is bound or
  595. * <code>InetAddress.anyLocalAddress()</code>
  596. * if the socket is not bound yet.
  597. * @since JDK1.1
  598. */
  599. public InetAddress getLocalAddress() {
  600. // This is for backward compatibility
  601. if (!isBound())
  602. return InetAddress.anyLocalAddress();
  603. InetAddress in = null;
  604. try {
  605. in = (InetAddress) getImpl().getOption(SocketOptions.SO_BINDADDR);
  606. if (in.isAnyLocalAddress()) {
  607. in = InetAddress.anyLocalAddress();
  608. }
  609. } catch (Exception e) {
  610. in = InetAddress.anyLocalAddress(); // "0.0.0.0"
  611. }
  612. return in;
  613. }
  614. /**
  615. * Returns the remote port number to which this socket is connected.
  616. *
  617. * @return the remote port number to which this socket is connected, or
  618. * 0 if the socket is not connected yet.
  619. */
  620. public int getPort() {
  621. if (!isConnected())
  622. return 0;
  623. try {
  624. return getImpl().getPort();
  625. } catch (SocketException e) {
  626. // Shouldn't happen as we're connected
  627. }
  628. return -1;
  629. }
  630. /**
  631. * Returns the local port number to which this socket is bound.
  632. *
  633. * @return the local port number to which this socket is bound or -1
  634. * if the socket is not bound yet.
  635. */
  636. public int getLocalPort() {
  637. if (!isBound())
  638. return -1;
  639. try {
  640. return getImpl().getLocalPort();
  641. } catch(SocketException e) {
  642. // shouldn't happen as we're bound
  643. }
  644. return -1;
  645. }
  646. /**
  647. * Returns the address of the endpoint this socket is connected to, or
  648. * <code>null</code> if it is unconnected.
  649. *
  650. * @return a <code>SocketAddress</code> reprensenting the remote endpoint of this
  651. * socket, or <code>null</code> if it is not connected yet.
  652. * @see #getInetAddress()
  653. * @see #getPort()
  654. * @see #connect(SocketAddress, int)
  655. * @see #connect(SocketAddress)
  656. * @since 1.4
  657. */
  658. public SocketAddress getRemoteSocketAddress() {
  659. if (!isConnected())
  660. return null;
  661. return new InetSocketAddress(getInetAddress(), getPort());
  662. }
  663. /**
  664. * Returns the address of the endpoint this socket is bound to, or
  665. * <code>null</code> if it is not bound yet.
  666. *
  667. * @return a <code>SocketAddress</code> representing the local endpoint of this
  668. * socket, or <code>null</code> if it is not bound yet.
  669. * @see #getLocalAddress()
  670. * @see #getLocalPort()
  671. * @see #bind(SocketAddress)
  672. * @since 1.4
  673. */
  674. public SocketAddress getLocalSocketAddress() {
  675. if (!isBound())
  676. return null;
  677. return new InetSocketAddress(getLocalAddress(), getLocalPort());
  678. }
  679. /**
  680. * Returns the unique {@link java.nio.channels.SocketChannel SocketChannel}
  681. * object associated with this socket, if any.
  682. *
  683. * <p> A socket will have a channel if, and only if, the channel itself was
  684. * created via the {@link java.nio.channels.SocketChannel#open
  685. * SocketChannel.open} or {@link
  686. * java.nio.channels.ServerSocketChannel#accept ServerSocketChannel.accept}
  687. * methods.
  688. *
  689. * @return the socket channel associated with this socket,
  690. * or <tt>null</tt> if this socket was not created
  691. * for a channel
  692. *
  693. * @since 1.4
  694. * @spec JSR-51
  695. */
  696. public SocketChannel getChannel() {
  697. return null;
  698. }
  699. /**
  700. * Returns an input stream for this socket.
  701. *
  702. * <p> If this socket has an associated channel then the resulting input
  703. * stream delegates all of its operations to the channel. If the channel
  704. * is in non-blocking mode then the input stream's <tt>read</tt> operations
  705. * will throw an {@link java.nio.channels.IllegalBlockingModeException}.
  706. *
  707. * <p>Under abnormal conditions the underlying connection may be
  708. * broken by the remote host or the network software (for example
  709. * a connection reset in the case of TCP connections). When a
  710. * broken connection is detected by the network software the
  711. * following applies to the returned input stream :-
  712. *
  713. * <ul>
  714. *
  715. * <li><p>The network software may discard bytes that are buffered
  716. * by the socket. Bytes that aren't discarded by the network
  717. * software can be read using {@link java.io.InputStream#read read}.
  718. *
  719. * <li><p>If there are no bytes buffered on the socket, or all
  720. * buffered bytes have been consumed by
  721. * {@link java.io.InputStream#read read}, then all subsequent
  722. * calls to {@link java.io.InputStream#read read} will throw an
  723. * {@link java.io.IOException IOException}.
  724. *
  725. * <li><p>If there are no bytes buffered on the socket, and the
  726. * socket has not been closed using {@link #close close}, then
  727. * {@link java.io.InputStream#available available} will
  728. * return <code>0</code>.
  729. *
  730. * </ul>
  731. *
  732. * <p> Closing the returned {@link java.io.InputStream InputStream}
  733. * will close the associated socket.
  734. *
  735. * @return an input stream for reading bytes from this socket.
  736. * @exception IOException if an I/O error occurs when creating the
  737. * input stream, the socket is closed, the socket is
  738. * not connected, or the socket input has been shutdown
  739. * using {@link #shutdownInput()}
  740. *
  741. * @revised 1.4
  742. * @spec JSR-51
  743. */
  744. public InputStream getInputStream() throws IOException {
  745. if (isClosed())
  746. throw new SocketException("Socket is closed");
  747. if (!isConnected())
  748. throw new SocketException("Socket is not connected");
  749. if (isInputShutdown())
  750. throw new SocketException("Socket input is shutdown");
  751. final Socket s = this;
  752. InputStream is = null;
  753. try {
  754. is = (InputStream)
  755. AccessController.doPrivileged(new PrivilegedExceptionAction() {
  756. public Object run() throws IOException {
  757. return impl.getInputStream();
  758. }
  759. });
  760. } catch (java.security.PrivilegedActionException e) {
  761. throw (IOException) e.getException();
  762. }
  763. return is;
  764. }
  765. /**
  766. * Returns an output stream for this socket.
  767. *
  768. * <p> If this socket has an associated channel then the resulting output
  769. * stream delegates all of its operations to the channel. If the channel
  770. * is in non-blocking mode then the output stream's <tt>write</tt>
  771. * operations will throw an {@link
  772. * java.nio.channels.IllegalBlockingModeException}.
  773. *
  774. * <p> Closing the returned {@link java.io.OutputStream OutputStream}
  775. * will close the associated socket.
  776. *
  777. * @return an output stream for writing bytes to this socket.
  778. * @exception IOException if an I/O error occurs when creating the
  779. * output stream or if the socket is not connected.
  780. * @revised 1.4
  781. * @spec JSR-51
  782. */
  783. public OutputStream getOutputStream() throws IOException {
  784. if (isClosed())
  785. throw new SocketException("Socket is closed");
  786. if (!isConnected())
  787. throw new SocketException("Socket is not connected");
  788. if (isOutputShutdown())
  789. throw new SocketException("Socket output is shutdown");
  790. final Socket s = this;
  791. OutputStream os = null;
  792. try {
  793. os = (OutputStream)
  794. AccessController.doPrivileged(new PrivilegedExceptionAction() {
  795. public Object run() throws IOException {
  796. return impl.getOutputStream();
  797. }
  798. });
  799. } catch (java.security.PrivilegedActionException e) {
  800. throw (IOException) e.getException();
  801. }
  802. return os;
  803. }
  804. /**
  805. * Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm).
  806. *
  807. * @param on <code>true</code> to enable TCP_NODELAY,
  808. * <code>false</code> to disable.
  809. *
  810. * @exception SocketException if there is an error
  811. * in the underlying protocol, such as a TCP error.
  812. *
  813. * @since JDK1.1
  814. *
  815. * @see #getTcpNoDelay()
  816. */
  817. public void setTcpNoDelay(boolean on) throws SocketException {
  818. if (isClosed())
  819. throw new SocketException("Socket is closed");
  820. getImpl().setOption(SocketOptions.TCP_NODELAY, Boolean.valueOf(on));
  821. }
  822. /**
  823. * Tests if TCP_NODELAY is enabled.
  824. *
  825. * @return a <code>boolean</code> indicating whether or not TCP_NODELAY is enabled.
  826. * @exception SocketException if there is an error
  827. * in the underlying protocol, such as a TCP error.
  828. * @since JDK1.1
  829. * @see #setTcpNoDelay(boolean)
  830. */
  831. public boolean getTcpNoDelay() throws SocketException {
  832. if (isClosed())
  833. throw new SocketException("Socket is closed");
  834. return ((Boolean) getImpl().getOption(SocketOptions.TCP_NODELAY)).booleanValue();
  835. }
  836. /**
  837. * Enable/disable SO_LINGER with the specified linger time in seconds.
  838. * The maximum timeout value is platform specific.
  839. *
  840. * The setting only affects socket close.
  841. *
  842. * @param on whether or not to linger on.
  843. * @param linger how long to linger for, if on is true.
  844. * @exception SocketException if there is an error
  845. * in the underlying protocol, such as a TCP error.
  846. * @exception IllegalArgumentException if the linger value is negative.
  847. * @since JDK1.1
  848. * @see #getSoLinger()
  849. */
  850. public void setSoLinger(boolean on, int linger) throws SocketException {
  851. if (isClosed())
  852. throw new SocketException("Socket is closed");
  853. if (!on) {
  854. getImpl().setOption(SocketOptions.SO_LINGER, new Boolean(on));
  855. } else {
  856. if (linger < 0) {
  857. throw new IllegalArgumentException("invalid value for SO_LINGER");
  858. }
  859. if (linger > 65535)
  860. linger = 65535;
  861. getImpl().setOption(SocketOptions.SO_LINGER, new Integer(linger));
  862. }
  863. }
  864. /**
  865. * Returns setting for SO_LINGER. -1 returns implies that the
  866. * option is disabled.
  867. *
  868. * The setting only affects socket close.
  869. *
  870. * @return the setting for SO_LINGER.
  871. * @exception SocketException if there is an error
  872. * in the underlying protocol, such as a TCP error.
  873. * @since JDK1.1
  874. * @see #setSoLinger(boolean, int)
  875. */
  876. public int getSoLinger() throws SocketException {
  877. if (isClosed())
  878. throw new SocketException("Socket is closed");
  879. Object o = getImpl().getOption(SocketOptions.SO_LINGER);
  880. if (o instanceof Integer) {
  881. return ((Integer) o).intValue();
  882. } else {
  883. return -1;
  884. }
  885. }
  886. /**
  887. * Send one byte of urgent data on the socket. The byte to be sent is the lowest eight
  888. * bits of the data parameter. The urgent byte is
  889. * sent after any preceding writes to the socket OutputStream
  890. * and before any future writes to the OutputStream.
  891. * @param data The byte of data to send
  892. * @exception IOException if there is an error
  893. * sending the data.
  894. * @since 1.4
  895. */
  896. public void sendUrgentData (int data) throws IOException {
  897. if (!getImpl().supportsUrgentData ()) {
  898. throw new SocketException ("Urgent data not supported");
  899. }
  900. getImpl().sendUrgentData (data);
  901. }
  902. /**
  903. * Enable/disable OOBINLINE (receipt of TCP urgent data)
  904. *
  905. * By default, this option is disabled and TCP urgent data received on a
  906. * socket is silently discarded. If the user wishes to receive urgent data, then
  907. * this option must be enabled. When enabled, urgent data is received
  908. * inline with normal data.
  909. * <p>
  910. * Note, only limited support is provided for handling incoming urgent
  911. * data. In particular, no notification of incoming urgent data is provided
  912. * and there is no capability to distinguish between normal data and urgent
  913. * data unless provided by a higher level protocol.
  914. *
  915. * @param on <code>true</code> to enable OOBINLINE,
  916. * <code>false</code> to disable.
  917. *
  918. * @exception SocketException if there is an error
  919. * in the underlying protocol, such as a TCP error.
  920. *
  921. * @since 1.4
  922. *
  923. * @see #getOOBInline()
  924. */
  925. public void setOOBInline(boolean on) throws SocketException {
  926. if (isClosed())
  927. throw new SocketException("Socket is closed");
  928. getImpl().setOption(SocketOptions.SO_OOBINLINE, Boolean.valueOf(on));
  929. }
  930. /**
  931. * Tests if OOBINLINE is enabled.
  932. *
  933. * @return a <code>boolean</code> indicating whether or not OOBINLINE is enabled.
  934. * @exception SocketException if there is an error
  935. * in the underlying protocol, such as a TCP error.
  936. * @since 1.4
  937. * @see #setOOBInline(boolean)
  938. */
  939. public boolean getOOBInline() throws SocketException {
  940. if (isClosed())
  941. throw new SocketException("Socket is closed");
  942. return ((Boolean) getImpl().getOption(SocketOptions.SO_OOBINLINE)).booleanValue();
  943. }
  944. /**
  945. * Enable/disable SO_TIMEOUT with the specified timeout, in
  946. * milliseconds. With this option set to a non-zero timeout,
  947. * a read() call on the InputStream associated with this Socket
  948. * will block for only this amount of time. If the timeout expires,
  949. * a <B>java.net.SocketTimeoutException</B> is raised, though the
  950. * Socket is still valid. The option <B>must</B> be enabled
  951. * prior to entering the blocking operation to have effect. The
  952. * timeout must be > 0.
  953. * A timeout of zero is interpreted as an infinite timeout.
  954. * @param timeout the specified timeout, in milliseconds.
  955. * @exception SocketException if there is an error
  956. * in the underlying protocol, such as a TCP error.
  957. * @since JDK 1.1
  958. * @see #getSoTimeout()
  959. */
  960. public synchronized void setSoTimeout(int timeout) throws SocketException {
  961. if (isClosed())
  962. throw new SocketException("Socket is closed");
  963. if (timeout < 0)
  964. throw new IllegalArgumentException("timeout can't be negative");
  965. getImpl().setOption(SocketOptions.SO_TIMEOUT, new Integer(timeout));
  966. }
  967. /**
  968. * Returns setting for SO_TIMEOUT. 0 returns implies that the
  969. * option is disabled (i.e., timeout of infinity).
  970. * @return the setting for SO_TIMEOUT
  971. * @exception SocketException if there is an error
  972. * in the underlying protocol, such as a TCP error.
  973. * @since JDK1.1
  974. * @see #setSoTimeout(int)
  975. */
  976. public synchronized int getSoTimeout() throws SocketException {
  977. if (isClosed())
  978. throw new SocketException("Socket is closed");
  979. Object o = getImpl().getOption(SocketOptions.SO_TIMEOUT);
  980. /* extra type safety */
  981. if (o instanceof Integer) {
  982. return ((Integer) o).intValue();
  983. } else {
  984. return 0;
  985. }
  986. }
  987. /**
  988. * Sets the SO_SNDBUF option to the specified value for this
  989. * <tt>Socket</tt>. The SO_SNDBUF option is used by the platform's
  990. * networking code as a hint for the size to set
  991. * the underlying network I/O buffers.
  992. *
  993. * <p>Because SO_SNDBUF is a hint, applications that want to
  994. * verify what size the buffers were set to should call
  995. * {@link #getSendBufferSize()}.
  996. *
  997. * @exception SocketException if there is an error
  998. * in the underlying protocol, such as a TCP error.
  999. *
  1000. * @param size the size to which to set the send buffer
  1001. * size. This value must be greater than 0.
  1002. *
  1003. * @exception IllegalArgumentException if the
  1004. * value is 0 or is negative.
  1005. *
  1006. * @see #getSendBufferSize()
  1007. * @since 1.2
  1008. */
  1009. public synchronized void setSendBufferSize(int size)
  1010. throws SocketException{
  1011. if (!(size > 0)) {
  1012. throw new IllegalArgumentException("negative send size");
  1013. }
  1014. if (isClosed())
  1015. throw new SocketException("Socket is closed");
  1016. getImpl().setOption(SocketOptions.SO_SNDBUF, new Integer(size));
  1017. }
  1018. /**
  1019. * Get value of the SO_SNDBUF option for this <tt>Socket</tt>,
  1020. * that is the buffer size used by the platform
  1021. * for output on this <tt>Socket</tt>.
  1022. * @return the value of the SO_SNDBUF option for this <tt>Socket</tt>.
  1023. *
  1024. * @exception SocketException if there is an error
  1025. * in the underlying protocol, such as a TCP error.
  1026. *
  1027. * @see #setSendBufferSize(int)
  1028. * @since 1.2
  1029. */
  1030. public synchronized int getSendBufferSize() throws SocketException {
  1031. if (isClosed())
  1032. throw new SocketException("Socket is closed");
  1033. int result = 0;
  1034. Object o = getImpl().getOption(SocketOptions.SO_SNDBUF);
  1035. if (o instanceof Integer) {
  1036. result = ((Integer)o).intValue();
  1037. }
  1038. return result;
  1039. }
  1040. /**
  1041. * Sets the SO_RCVBUF option to the specified value for this
  1042. * <tt>Socket</tt>. The SO_RCVBUF option is used by the platform's
  1043. * networking code as a hint for the size to set
  1044. * the underlying network I/O buffers.
  1045. *
  1046. * <p>Increasing the receive buffer size can increase the performance of
  1047. * network I/O for high-volume connection, while decreasing it can
  1048. * help reduce the backlog of incoming data.
  1049. *
  1050. * <p>Because SO_RCVBUF is a hint, applications that want to
  1051. * verify what size the buffers were set to should call
  1052. * {@link #getReceiveBufferSize()}.
  1053. *
  1054. * <p>The value of SO_RCVBUF is also used to set the TCP receive window
  1055. * that is advertized to the remote peer. Generally, the window size
  1056. * can be modified at any time when a socket is connected. However, if
  1057. * a receive window larger than 64K is required then this must be requested
  1058. * <B>before</B> the socket is connected to the remote peer. There are two
  1059. * cases to be aware of:<p>
  1060. * <ol>
  1061. * <li>For sockets accepted from a ServerSocket, this must be done by calling
  1062. * {@link ServerSocket#setReceiveBufferSize(int)} before the ServerSocket
  1063. * is bound to a local address.<p></li>
  1064. * <li>For client sockets, setReceiveBufferSize() must be called before
  1065. * connecting the socket to its remote peer.<p></li></ol>
  1066. * @param size the size to which to set the receive buffer
  1067. * size. This value must be greater than 0.
  1068. *
  1069. * @exception IllegalArgumentException if the value is 0 or is
  1070. * negative.
  1071. *
  1072. * @exception SocketException if there is an error
  1073. * in the underlying protocol, such as a TCP error.
  1074. *
  1075. * @see #getReceiveBufferSize()
  1076. * @see ServerSocket#setReceiveBufferSize(int)
  1077. * @since 1.2
  1078. */
  1079. public synchronized void setReceiveBufferSize(int size)
  1080. throws SocketException{
  1081. if (size <= 0) {
  1082. throw new IllegalArgumentException("invalid receive size");
  1083. }
  1084. if (isClosed())
  1085. throw new SocketException("Socket is closed");
  1086. getImpl().setOption(SocketOptions.SO_RCVBUF, new Integer(size));
  1087. }
  1088. /**
  1089. * Gets the value of the SO_RCVBUF option for this <tt>Socket</tt>,
  1090. * that is the buffer size used by the platform for
  1091. * input on this <tt>Socket</tt>.
  1092. *
  1093. * @return the value of the SO_RCVBUF option for this <tt>Socket</tt>.
  1094. * @exception SocketException if there is an error
  1095. * in the underlying protocol, such as a TCP error.
  1096. * @see #setReceiveBufferSize(int)
  1097. * @since 1.2
  1098. */
  1099. public synchronized int getReceiveBufferSize()
  1100. throws SocketException{
  1101. if (isClosed())
  1102. throw new SocketException("Socket is closed");
  1103. int result = 0;
  1104. Object o = getImpl().getOption(SocketOptions.SO_RCVBUF);
  1105. if (o instanceof Integer) {
  1106. result = ((Integer)o).intValue();
  1107. }
  1108. return result;
  1109. }
  1110. /**
  1111. * Enable/disable SO_KEEPALIVE.
  1112. *
  1113. * @param on whether or not to have socket keep alive turned on.
  1114. * @exception SocketException if there is an error
  1115. * in the underlying protocol, such as a TCP error.
  1116. * @since 1.3
  1117. * @see #getKeepAlive()
  1118. */
  1119. public void setKeepAlive(boolean on) throws SocketException {
  1120. if (isClosed())
  1121. throw new SocketException("Socket is closed");
  1122. getImpl().setOption(SocketOptions.SO_KEEPALIVE, Boolean.valueOf(on));
  1123. }
  1124. /**
  1125. * Tests if SO_KEEPALIVE is enabled.
  1126. *
  1127. * @return a <code>boolean</code> indicating whether or not SO_KEEPALIVE is enabled.
  1128. * @exception SocketException if there is an error
  1129. * in the underlying protocol, such as a TCP error.
  1130. * @since 1.3
  1131. * @see #setKeepAlive(boolean)
  1132. */
  1133. public boolean getKeepAlive() throws SocketException {
  1134. if (isClosed())
  1135. throw new SocketException("Socket is closed");
  1136. return ((Boolean) getImpl().getOption(SocketOptions.SO_KEEPALIVE)).booleanValue();
  1137. }
  1138. /**
  1139. * Sets traffic class or type-of-service octet in the IP
  1140. * header for packets sent from this Socket.
  1141. * As the underlying network implementation may ignore this
  1142. * value applications should consider it a hint.
  1143. *
  1144. * <P> The tc <B>must</B> be in the range <code> 0 <= tc <=
  1145. * 255</code> or an IllegalArgumentException will be thrown.
  1146. * <p>Notes:
  1147. * <p> For Internet Protocol v4 the value consists of an octet
  1148. * with precedence and TOS fields as detailed in RFC 1349. The
  1149. * TOS field is bitset created by bitwise-or'ing values such
  1150. * the following :-
  1151. * <p>
  1152. * <UL>
  1153. * <LI><CODE>IPTOS_LOWCOST (0x02)</CODE></LI>
  1154. * <LI><CODE>IPTOS_RELIABILITY (0x04)</CODE></LI>
  1155. * <LI><CODE>IPTOS_THROUGHPUT (0x08)</CODE></LI>
  1156. * <LI><CODE>IPTOS_LOWDELAY (0x10)</CODE></LI>
  1157. * </UL>
  1158. * The last low order bit is always ignored as this
  1159. * corresponds to the MBZ (must be zero) bit.
  1160. * <p>
  1161. * Setting bits in the precedence field may result in a
  1162. * SocketException indicating that the operation is not
  1163. * permitted.
  1164. * <p>
  1165. * As RFC 1122 section 4.2.4.2 indicates, a compliant TCP
  1166. * implementation should, but is not required to, let application
  1167. * change the TOS field during the lifetime of a connection.
  1168. * So whether the type-of-service field can be changed after the
  1169. * TCP connection has been established depends on the implementation
  1170. * in the underlying platform. Applications should not assume that
  1171. * they can change the TOS field after the connection.
  1172. * <p>
  1173. * For Internet Protocol v6 <code>tc</code> is the value that
  1174. * would be placed into the sin6_flowinfo field of the IP header.
  1175. *
  1176. * @param tc an <code>int</code> value for the bitset.
  1177. * @throws SocketException if there is an error setting the
  1178. * traffic class or type-of-service
  1179. * @since 1.4
  1180. * @see #getTrafficClass
  1181. */
  1182. public void setTrafficClass(int tc) throws SocketException {
  1183. if (tc < 0 || tc > 255)
  1184. throw new IllegalArgumentException("tc is not in range 0 -- 255");
  1185. if (isClosed())
  1186. throw new SocketException("Socket is closed");
  1187. getImpl().setOption(SocketOptions.IP_TOS, new Integer(tc));
  1188. }
  1189. /**
  1190. * Gets traffic class or type-of-service in the IP header
  1191. * for packets sent from this Socket
  1192. * <p>
  1193. * As the underlying network implementation may ignore the
  1194. * traffic class or type-of-service set using {@link #setTrafficClass(int)}
  1195. * this method may return a different value than was previously
  1196. * set using the {@link #setTrafficClass(int)} method on this Socket.
  1197. *
  1198. * @return the traffic class or type-of-service already set
  1199. * @throws SocketException if there is an error obtaining the
  1200. * traffic class or type-of-service value.
  1201. * @since 1.4
  1202. * @see #setTrafficClass(int)
  1203. */
  1204. public int getTrafficClass() throws SocketException {
  1205. return ((Integer) (getImpl().getOption(SocketOptions.IP_TOS))).intValue();
  1206. }
  1207. /**
  1208. * Enable/disable the SO_REUSEADDR socket option.
  1209. * <p>
  1210. * When a TCP connection is closed the connection may remain
  1211. * in a timeout state for a period of time after the connection
  1212. * is closed (typically known as the <tt>TIME_WAIT</tt> state
  1213. * or <tt>2MSL</tt> wait state).
  1214. * For applications using a well known socket address or port
  1215. * it may not be possible to bind a socket to the required
  1216. * <tt>SocketAddress</tt> if there is a connection in the
  1217. * timeout state involving the socket address or port.
  1218. * <p>
  1219. * Enabling <tt>SO_REUSEADDR</tt> prior to binding the socket
  1220. * using {@link #bind(SocketAddress)} allows the socket to be
  1221. * bound even though a previous connection is in a timeout
  1222. * state.
  1223. * <p>
  1224. * When a <tt>Socket</tt> is created the initial setting
  1225. * of <tt>SO_REUSEADDR</tt> is disabled.
  1226. * <p>
  1227. * The behaviour when <tt>SO_REUSEADDR</tt> is enabled or
  1228. * disabled after a socket is bound (See {@link #isBound()})
  1229. * is not defined.
  1230. *
  1231. * @param on whether to enable or disable the socket option
  1232. * @exception SocketException if an error occurs enabling or
  1233. * disabling the <tt>SO_RESUEADDR</tt> socket option,
  1234. * or the socket is closed.
  1235. * @since 1.4
  1236. * @see #getReuseAddress()
  1237. * @see #bind(SocketAddress)
  1238. * @see #isClosed()
  1239. * @see #isBound()
  1240. */
  1241. public void setReuseAddress(boolean on) throws SocketException {
  1242. if (isClosed())
  1243. throw new SocketException("Socket is closed");
  1244. getImpl().setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(on));
  1245. }
  1246. /**
  1247. * Tests if SO_REUSEADDR is enabled.
  1248. *
  1249. * @return a <code>boolean</code> indicating whether or not SO_REUSEADDR is enabled.
  1250. * @exception SocketException if there is an error
  1251. * in the underlying protocol, such as a TCP error.
  1252. * @since 1.4
  1253. * @see #setReuseAddress(boolean)
  1254. */
  1255. public boolean getReuseAddress() throws SocketException {
  1256. if (isClosed())
  1257. throw new SocketException("Socket is closed");
  1258. return ((Boolean) (getImpl().getOption(SocketOptions.SO_REUSEADDR))).booleanValue();
  1259. }
  1260. /**
  1261. * Closes this socket.
  1262. * <p>
  1263. * Any thread currently blocked in an I/O operation upon this socket
  1264. * will throw a {@link SocketException}.
  1265. * <p>
  1266. * Once a socket has been closed, it is not available for further networking
  1267. * use (i.e. can't be reconnected or rebound). A new socket needs to be
  1268. * created.
  1269. *
  1270. * <p> Closing this socket will also close the socket's
  1271. * {@link java.io.InputStream InputStream} and
  1272. * {@link java.io.OutputStream OutputStream}.
  1273. *
  1274. * <p> If this socket has an associated channel then the channel is closed
  1275. * as well.
  1276. *
  1277. * @exception IOException if an I/O error occurs when closing this socket.
  1278. * @revised 1.4
  1279. * @spec JSR-51
  1280. * @see #isClosed
  1281. */
  1282. public synchronized void close() throws IOException {
  1283. synchronized(closeLock) {
  1284. if (isClosed())
  1285. return;
  1286. if (created)
  1287. impl.close();
  1288. closed = true;
  1289. }
  1290. }
  1291. /**
  1292. * Places the input stream for this socket at "end of stream".
  1293. * Any data sent to the input stream side of the socket is acknowledged
  1294. * and then silently discarded.
  1295. * <p>
  1296. * If you read from a socket input stream after invoking
  1297. * shutdownInput() on the socket, the stream will return EOF.
  1298. *
  1299. * @exception IOException if an I/O error occurs when shutting down this
  1300. * socket.
  1301. *
  1302. * @since 1.3
  1303. * @see java.net.Socket#shutdownOutput()
  1304. * @see java.net.Socket#close()
  1305. * @see java.net.Socket#setSoLinger(boolean, int)
  1306. * @see #isInputShutdown
  1307. */
  1308. public void shutdownInput() throws IOException
  1309. {
  1310. if (isClosed())
  1311. throw new SocketException("Socket is closed");
  1312. if (!isConnected())
  1313. throw new SocketException("Socket is not connected");
  1314. if (isInputShutdown())
  1315. throw new SocketException("Socket input is already shutdown");
  1316. getImpl().shutdownInput();
  1317. shutIn = true;
  1318. }
  1319. /**
  1320. * Disables the output stream for this socket.
  1321. * For a TCP socket, any previously written data will be sent
  1322. * followed by TCP's normal connection termination sequence.
  1323. *
  1324. * If you write to a socket output stream after invoking
  1325. * shutdownOutput() on the socket, the stream will throw
  1326. * an IOException.
  1327. *
  1328. * @exception IOException if an I/O error occurs when shutting down this
  1329. * socket.
  1330. *
  1331. * @since 1.3
  1332. * @see java.net.Socket#shutdownInput()
  1333. * @see java.net.Socket#close()
  1334. * @see java.net.Socket#setSoLinger(boolean, int)
  1335. * @see #isOutputShutdown
  1336. */
  1337. public void shutdownOutput() throws IOException
  1338. {
  1339. if (isClosed())
  1340. throw new SocketException("Socket is closed");
  1341. if (!isConnected())
  1342. throw new SocketException("Socket is not connected");
  1343. if (isOutputShutdown())
  1344. throw new SocketException("Socket output is already shutdown");
  1345. getImpl().shutdownOutput();
  1346. shutOut = true;
  1347. }
  1348. /**
  1349. * Converts this socket to a <code>String</code>.
  1350. *
  1351. * @return a string representation of this socket.
  1352. */
  1353. public String toString() {
  1354. try {
  1355. if (isConnected())
  1356. return "Socket[addr=" + getImpl().getInetAddress() +
  1357. ",port=" + getImpl().getPort() +
  1358. ",localport=" + getImpl().getLocalPort() + "]";
  1359. } catch (SocketException e) {
  1360. }
  1361. return "Socket[unconnected]";
  1362. }
  1363. /**
  1364. * Returns the connection state of the socket.
  1365. *
  1366. * @return true if the socket successfuly connected to a server
  1367. * @since 1.4
  1368. */
  1369. public boolean isConnected() {
  1370. // Before 1.3 Sockets were always connected during creation
  1371. return connected || oldImpl;
  1372. }
  1373. /**
  1374. * Returns the binding state of the socket.
  1375. *
  1376. * @return true if the socket successfuly bound to an address
  1377. * @since 1.4
  1378. * @see #bind
  1379. */
  1380. public boolean isBound() {
  1381. // Before 1.3 Sockets were always bound during creation
  1382. return bound || oldImpl;
  1383. }
  1384. /**
  1385. * Returns the closed state of the socket.
  1386. *
  1387. * @return true if the socket has been closed
  1388. * @since 1.4
  1389. * @see #close
  1390. */
  1391. public boolean isClosed() {
  1392. synchronized(closeLock) {
  1393. return closed;
  1394. }
  1395. }
  1396. /**
  1397. * Returns whether the read-half of the socket connection is closed.
  1398. *
  1399. * @return true if the input of the socket has been shutdown
  1400. * @since 1.4
  1401. * @see #shutdownInput
  1402. */
  1403. public boolean isInputShutdown() {
  1404. return shutIn;
  1405. }
  1406. /**
  1407. * Returns whether the write-half of the socket connection is closed.
  1408. *
  1409. * @return true if the output of the socket has been shutdown
  1410. * @since 1.4
  1411. * @see #shutdownOutput
  1412. */
  1413. public boolean isOutputShutdown() {
  1414. return shutOut;
  1415. }
  1416. /**
  1417. * The factory for all client sockets.
  1418. */
  1419. private static SocketImplFactory factory = null;
  1420. /**
  1421. * Sets the client socket implementation factory for the
  1422. * application. The factory can be specified only once.
  1423. * <p>
  1424. * When an application creates a new client socket, the socket
  1425. * implementation factory's <code>createSocketImpl</code> method is
  1426. * called to create the actual socket implementation.
  1427. * <p>
  1428. * Passing <code>null</code> to the method is a no-op unless the factory
  1429. * was already set.
  1430. * <p>If there is a security manager, this method first calls
  1431. * the security manager's <code>checkSetFactory</code> method
  1432. * to ensure the operation is allowed.
  1433. * This could result in a SecurityException.
  1434. *
  1435. * @param fac the desired factory.
  1436. * @exception IOException if an I/O error occurs when setting the
  1437. * socket factory.
  1438. * @exception SocketException if the factory is already defined.
  1439. * @exception SecurityException if a security manager exists and its
  1440. * <code>checkSetFactory</code> method doesn't allow the operation.
  1441. * @see java.net.SocketImplFactory#createSocketImpl()
  1442. * @see SecurityManager#checkSetFactory
  1443. */
  1444. public static synchronized void setSocketImplFactory(SocketImplFactory fac)
  1445. throws IOException
  1446. {
  1447. if (factory != null) {
  1448. throw new SocketException("factory already defined");
  1449. }
  1450. SecurityManager security = System.getSecurityManager();
  1451. if (security != null) {
  1452. security.checkSetFactory();
  1453. }
  1454. factory = fac;
  1455. }
  1456. /**
  1457. * Sets performance preferences for this socket.
  1458. *
  1459. * <p> Sockets use the TCP/IP protocol by default. Some implementations
  1460. * may offer alternative protocols which have different performance
  1461. * characteristics than TCP/IP. This method allows the application to
  1462. * express its own preferences as to how these tradeoffs should be made
  1463. * when the implementation chooses from the available protocols.
  1464. *
  1465. * <p> Performance preferences are described by three integers
  1466. * whose values indicate the relative importance of short connection time,
  1467. * low latency, and high bandwidth. The absolute values of the integers
  1468. * are irrelevant; in order to choose a protocol the values are simply
  1469. * compared, with larger values indicating stronger preferences. Negative
  1470. * values represent a lower priority than positive values. If the
  1471. * application prefers short connection time over both low latency and high
  1472. * bandwidth, for example, then it could invoke this method with the values
  1473. * <tt>(1, 0, 0)</tt>. If the application prefers high bandwidth above low
  1474. * latency, and low latency above short connection time, then it could
  1475. * invoke this method with the values <tt>(0, 1, 2)</tt>.
  1476. *
  1477. * <p> Invoking this method after this socket has been connected
  1478. * will have no effect.
  1479. *
  1480. * @param connectionTime
  1481. * An <tt>int</tt> expressing the relative importance of a short
  1482. * connection time
  1483. *
  1484. * @param latency
  1485. * An <tt>int</tt> expressing the relative importance of low
  1486. * latency
  1487. *
  1488. * @param bandwidth
  1489. * An <tt>int</tt> expressing the relative importance of high
  1490. * bandwidth
  1491. *
  1492. * @since 1.5
  1493. */
  1494. public void setPerformancePreferences(int connectionTime,
  1495. int latency,
  1496. int bandwidth)
  1497. {
  1498. /* Not implemented yet */
  1499. }
  1500. }