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