⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 datagramsocket.java

📁 俄罗斯高人Mamaich的Pocket gcc编译器(运行在PocketPC上)的全部源代码。
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* DatagramSocket.java -- A class to model UDP sockets   Copyright (C) 1998, 1999, 2000, 2002 Free Software Foundation, Inc.This file is part of GNU Classpath.GNU Classpath is free software; you can redistribute it and/or modifyit under the terms of the GNU General Public License as published bythe Free Software Foundation; either version 2, or (at your option)any later version. GNU Classpath is distributed in the hope that it will be useful, butWITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNUGeneral Public License for more details.You should have received a copy of the GNU General Public Licensealong with GNU Classpath; see the file COPYING.  If not, write to theFree Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA02111-1307 USA.Linking this library statically or dynamically with other modules ismaking a combined work based on this library.  Thus, the terms andconditions of the GNU General Public License cover the wholecombination.As a special exception, the copyright holders of this library give youpermission to link this library with independent modules to produce anexecutable, regardless of the license terms of these independentmodules, and to copy and distribute the resulting executable underterms of your choice, provided that you also meet, for each linkedindependent module, the terms and conditions of the license of thatmodule.  An independent module is a module which is not derived fromor based on this library.  If you modify this library, you may extendthis exception to your version of the library, but you are notobligated to do so.  If you do not wish to do so, delete thisexception statement from your version. */package java.net;import java.io.IOException;import java.nio.channels.DatagramChannel;import java.nio.channels.IllegalBlockingModeException;/** * Written using on-line Java Platform 1.2 API Specification, as well * as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998). * Status:  Believed complete and correct. *//** * This class models a connectionless datagram socket that sends  * individual packets of data across the network.  In the TCP/IP world, * this means UDP.  Datagram packets do not have guaranteed delivery, * or any guarantee about the order the data will be received on the * remote host. *  * @author Aaron M. Renn (arenn@urbanophile.com) * @author Warren Levy (warrenl@cygnus.com) * @date May 3, 1999. */public class DatagramSocket{  /**   * This is the user DatagramSocketImplFactory for this class.  If this   * variable is null, a default factory is used.   */  static DatagramSocketImplFactory factory;	    /**   * This is the implementation object used by this socket.   */  DatagramSocketImpl impl;  /**   * The unique DatagramChannel object associated with this datagram socket,   * or null.   */  DatagramChannel ch;  /**   * This is the address we are "connected" to   */  private InetAddress remoteAddress;  /**   * This is the port we are "connected" to   */  private int remotePort = -1;  /**   * Indicates when the socket is closed.   */  private boolean closed = false;  /**   * Creates a DatagramSocket from a specified DatagramSocketImpl instance   *   * @param impl The DatagramSocketImpl the socket will be created from   *    * @since 1.4   */  protected DatagramSocket (DatagramSocketImpl impl)  {    this.impl = impl;    this.remoteAddress = null;    this.remotePort = -1;  }  /**   * Initializes a new instance of <code>DatagramSocket</code> that binds to    * a random port and every address on the local machine.   *   * @exception SocketException If an error occurs.   * @exception SecurityException If a security manager exists and   * its checkListen method doesn't allow the operation.   */  public DatagramSocket() throws SocketException  {    this(0, null);  }  /**   * Initializes a new instance of <code>DatagramSocket</code> that binds to    * the specified port and every address on the local machine.   *   * @param port The local port number to bind to.   *   * @exception SecurityException If a security manager exists and its   * checkListen method doesn't allow the operation.   * @exception SocketException If an error occurs.   */  public DatagramSocket(int port) throws SocketException  {    this(port, null);  }  /**   * Initializes a new instance of <code>DatagramSocket</code> that binds to    * the specified local port and address.   *   * @param port The local port number to bind to.   * @param laddr The local address to bind to.   *   * @exception SecurityException If a security manager exists and its   * checkListen method doesn't allow the operation.   * @exception SocketException If an error occurs.   */  public DatagramSocket(int port, InetAddress laddr) throws SocketException  {    if (port < 0 || port > 65535)      throw new IllegalArgumentException("Invalid port: " + port);    SecurityManager s = System.getSecurityManager();    if (s != null)      s.checkListen(port);    String propVal = System.getProperty("impl.prefix");    if (propVal == null || propVal.equals(""))      impl = new PlainDatagramSocketImpl();    else      try	{          impl = (DatagramSocketImpl) Class.forName            ("java.net." + propVal + "DatagramSocketImpl").newInstance();	}      catch (Exception e)	{	  System.err.println("Could not instantiate class: java.net." +	    propVal + "DatagramSocketImpl");	  impl = new PlainDatagramSocketImpl();	}    impl.create();    // For multicasting, set the socket to be reused (Stevens pp. 195-6).    if (this instanceof MulticastSocket)      impl.setOption(SocketOptions.SO_REUSEADDR, new Boolean(true));    impl.bind(port, laddr == null ? InetAddress.ANY_IF : laddr);        remoteAddress = null;    remotePort = -1;  }  /**   * Initializes a new instance of <code>DatagramSocket</code> that binds to    * the specified local port and address.   *   * @param port The local port number to bind to.   * @param laddr The local address to bind to.   *   * @exception SecurityException If a security manager exists and its   * checkListen method doesn't allow the operation.   * @exception SocketException If an error occurs.   *   * @since 1.4   */  public DatagramSocket (SocketAddress address) throws SocketException  {    this (((InetSocketAddress) address).getPort (),          ((InetSocketAddress) address).getAddress ());  }    /**   * Closes this datagram socket.   */  public void close()  {    if (!closed)      {        impl.close();        remoteAddress = null;        remotePort = -1;        closed = true;      }  }  /**   * This method returns the remote address to which this socket is    * connected.  If this socket is not connected, then this method will   * return <code>null</code>.   *    * @return The remote address.   *   * @since 1.2   */  public InetAddress getInetAddress()  {    return remoteAddress;  }  /**   * This method returns the remote port to which this socket is   * connected.  If this socket is not connected, then this method will   * return -1.   *    * @return The remote port.   *   * @since 1.2   */  public int getPort()  {    return remotePort;  }  /**   * Returns the local address this datagram socket is bound to.   *    * @since 1.1   */  public InetAddress getLocalAddress()  {    // FIXME: JCL p. 510 says this should call checkConnect.  But what    // string should be used as the hostname?  Maybe this is just a side    // effect of calling InetAddress.getLocalHost.    //    // And is getOption with SO_BINDADDR the right way to get the address?    // Doesn't seem to be since this method doesn't throw a SocketException    // and SO_BINADDR can throw one.    //    // Also see RETURNS section in JCL p. 510 about returning any local    // addr "if the current execution context is not allowed to connect to    // the network interface that is actually bound to this datagram socket."    // How is that done?  via InetAddress.getLocalHost?  But that throws    // an UnknownHostException and this method doesn't.    //    // if (s != null)    //   s.checkConnect("localhost", -1);    try      {        return (InetAddress)impl.getOption(SocketOptions.SO_BINDADDR);      }    catch (SocketException ex)      {      }    try      {        return InetAddress.getLocalHost();      }    catch (UnknownHostException ex)      {        // FIXME: This should never happen, so how can we avoid this construct?        return null;      }  }  /**   * Returns the local port this socket is bound to.   *   * @return The local port number.   */  public int getLocalPort()  {    if (!isBound ())      return -1;    return impl.getLocalPort();  }  /**   * Returns the value of the socket's SO_TIMEOUT setting.  If this method   * returns 0 then SO_TIMEOUT is disabled.   *   * @return The current timeout in milliseconds.   *   * @exception SocketException If an error occurs.   *    * @since 1.1   */  public synchronized int getSoTimeout() throws SocketException  {    if (impl == null)      throw new SocketException ("Cannot initialize Socket implementation");    Object timeout = impl.getOption(SocketOptions.SO_TIMEOUT);    if (timeout instanceof Integer)       return ((Integer)timeout).intValue();    else      return 0;  }  /**   * Sets the value of the socket's SO_TIMEOUT value.  A value of 0 will   * disable SO_TIMEOUT.  Any other value is the number of milliseconds   * a socket read/write will block before timing out.   *   * @param timeout The new SO_TIMEOUT value in milliseconds.   *   * @exception SocketException If an error occurs.   *   * @since 1.1   */  public synchronized void setSoTimeout(int timeout) throws SocketException  {    if (timeout < 0)      throw new IllegalArgumentException("Invalid timeout: " + timeout);    impl.setOption(SocketOptions.SO_TIMEOUT, new Integer(timeout));  }  /**   * This method returns the value of the system level socket option   * SO_SNDBUF, which is used by the operating system to tune buffer   * sizes for data transfers.   *   * @return The send buffer size.   *   * @exception SocketException If an error occurs.   *   * @since 1.2   */  public int getSendBufferSize() throws SocketException  {    if (impl == null)      throw new SocketException ("Cannot initialize Socket implementation");    Object obj = impl.getOption(SocketOptions.SO_SNDBUF);    if (obj instanceof Integer)      return(((Integer)obj).intValue());    else      throw new SocketException("Unexpected type");  }  /**   * This method sets the value for the system level socket option   * SO_SNDBUF to the specified value.  Note that valid values for this   * option are specific to a given operating system.   *   * @param size The new send buffer size.   *   * @exception SocketException If an error occurs.   * @exception IllegalArgumentException If size is 0 or negative.   *   * @since 1.2   */  public void setSendBufferSize(int size) throws SocketException  {    if (size < 0)      throw new IllegalArgumentException("Buffer size is less than 0");      impl.setOption(SocketOptions.SO_SNDBUF, new Integer(size));  }  /**   * This method returns the value of the system level socket option   * SO_RCVBUF, which is used by the operating system to tune buffer   * sizes for data transfers.   *   * @return The receive buffer size.   *   * @exception SocketException If an error occurs.   *   * @since 1.2   */  public int getReceiveBufferSize() throws SocketException  {    if (impl == null)      throw new SocketException ("Cannot initialize Socket implementation");    Object obj = impl.getOption(SocketOptions.SO_RCVBUF);      if (obj instanceof Integer)      return(((Integer)obj).intValue());    else       throw new SocketException("Unexpected type");  }  /**   * This method sets the value for the system level socket option   * SO_RCVBUF to the specified value.  Note that valid values for this   * option are specific to a given operating system.   *   * @param size The new receive buffer size.   *   * @exception SocketException If an error occurs.   * @exception IllegalArgumentException If size is 0 or negative.   *    * @since 1.2   */  public void setReceiveBufferSize(int size) throws SocketException

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -