`

JAVA Socket的方法说明

阅读更多
    /**
     * Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm).
     *
     * @param on <code>true</code> to enable TCP_NODELAY, 
     * <code>false</code> to disable.
     *
     * @exception SocketException if there is an error 
     * in the underlying protocol, such as a TCP error.
     * 
     * @since   JDK1.1
     *
     * @see #getTcpNoDelay()
     */
    public void setTcpNoDelay(boolean on) throws SocketException

  •  setTcpNoDelay

这是一个设置是否启用Nagle算法,Nagle算法是一个TCP层的通信流量的拥塞控制算法(Flow Control),在大学的计算机网络课本上都会提到这个慢启动(Slow start)”和“拥塞避免(Congestion avoidance)”,“快速重传(Fast retransmit)”、“快速恢复(Fast Recovery)”。

缺省的算法实现一般都是启用的。这样可以处理,防止发送方处理过快,接受方数据处理不过来的情况。但是,如果在实时处理上,通常发送方不需要关心接收方是否能够及时处理数据,因此可能需要设置这个参数。、

       如果设置ture,不启用Nagle‘s algorithm

       如果为false,启用Nagle's algorithm

       缺省值,依赖于socket的具体实现,通常是false。即启用Nagle

-----------------------------------------------------------------------------------------------------------

 

   /**
     * Send one byte of urgent data on the socket. The byte to be sent is the lowest eight
     * bits of the data parameter. The urgent byte is
     * sent after any preceding writes to the socket OutputStream
     * and before any future writes to the OutputStream.
     * @param data The byte of data to send
     * @exception IOException if there is an error
     *  sending the data.
     * @since 1.4
     */
    public void sendUrgentData (int data) throws IOException 

 

  •  sendUrgentData

 设置紧急数据包——在socket上发送一个byte的紧急数据,它会在所有socket的输出流(OutputStream),已经写入之后,但是在其他将要发送的数据之前。

     通常,发送紧急数据用于处理一些特殊情况。(如通知对方执行某个控制指令)。

    /**
     *  Enable/disable SO_TIMEOUT with the specified timeout, in
     *  milliseconds.  With this option set to a non-zero timeout,
     *  a read() call on the InputStream associated with this Socket
     *  will block for only this amount of time.  If the timeout expires,
     *  a <B>java.net.SocketTimeoutException</B> is raised, though the
     *  Socket is still valid. The option <B>must</B> be enabled
     *  prior to entering the blocking operation to have effect. The
     *  timeout must be > 0.
     *  A timeout of zero is interpreted as an infinite timeout.
     * @param timeout the specified timeout, in milliseconds.
     * @exception SocketException if there is an error
     * in the underlying protocol, such as a TCP error. 
     * @since   JDK 1.1
     * @see #getSoTimeout()
     */
    public synchronized void setSoTimeout(int timeout) throws SocketException

  

  •  setSoTimeout

设置超时时间,单位毫秒,这是一个同步方法。这个超时不同于应用层协议的超时,如http协议的超时。

 

作用:

如果socket在输入流inputstream执行了read()方法,那么最多等待timeout时间,如果超过这个timeout时间,程序会抛出SocketException异常,注,即使抛出了SocketException异常,该socket仍然是有效的!如果这个时候去重新连接统一端口的Socket,会失败。

如果参数设置为0,等同于无超时时间。

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics