Socket.Poll()

Socket.Poll()

public bool Poll (

                    int microSeconds,

                    SelectMode mode

)

MSDN:

Poll 方法将会检查 Socket 的状态。指定 selectMode 参数的 SelectMode.SelectRead,可确定 Socket 是否为可读。指定 SelectMode.SelectWrite,可确定 Socket 是否为可写。使用 SelectMode.SelectError 检测错误条件。Poll 将在指定的时段(以 microseconds 为单位)内阻止执行。如果希望无限期的等待响应,则将 microSeconds 设置为一个负整数。

 

int  microSeconds,

MSDN:

等待响应的时间(以微秒为单位)。

自己理解:

是Poll程序中断运行时间。 如microseconds=1000;Poll阻塞1000微秒,microseconds<0将无限等待响应。

 

SelectMode mode

 public enum SelectMode

 {

     SelectRead = 0,  //     读状态模式。

     SelectWrite = 1, //     写状态模式。

     SelectError = 2, //     错误状态模式。

 }

MSDN:

模式(SelectMode

返回(return

SelectRead

1.  如果已调用Listen并且有挂起的连接,则为true。

2.如果有数据可供读取,则为true。

3.如果连接已关闭、重置或终止,则返回true。

SelectWrite

1.  如果正在处理Connect并且连接已成功,则为true。

2.  如果可以发送数据,则返回true。

SelectError

1.  如果正在处理不阻止的Connect,并且连接已失败,则为true。

2.  如果OutOfBandInline未设置,并且带外数据可用,则为true。

自己理解:

只对红色部分理解。

         2010.8.30

MSDN例子:

//Creates the Socket for sending data over TCP.

Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream,

   ProtocolType.Tcp );

 

// Connects to host using IPEndPoint.

s.Connect(EPhost);

if (!s.Connected)

{

   strRetPage = "Unable to connect to host";

}

// Use the SelectWrite enumeration to obtain Socket status.

 if(s.Poll(-1, SelectMode.SelectWrite)){

      Console.WriteLine("This Socket is writable.");

 }

 else if (s.Poll(-1, SelectMode.SelectRead)){

        Console.WriteLine("This Socket is readable." );

 }

 else if (s.Poll(-1, SelectMode.SelectError)){

      Console.WriteLine("This Socket has an error.");

 }

 

自己例子:

protected override void ProcMessage()

        {

            int microSeconds = 50;

            EndPoint senderRemote = socket.RemoteEndPoint;

            int dataLen, msgLen = 0;

            try

            {

                if (socket.Poll(microSeconds, SelectMode.SelectRead))

                {

                    dataLen = ReceiveFrom(m_ReceiveBuf, m_ReceiveBuf.Length, socket);

                    if (EClass.Message.Message.Valid(m_ReceiveBuf))

                        MessageParse(m_ReceiveBuf, dataLen, (IPEndPoint)senderRemote);

                }

            }

            catch (SocketException se)

            {

                SocketError err = se.SocketErrorCode;

            }

        }

 原文地址:http://blog.sina.com.cn/s/blog_43eee55a0100l87i.html

posted on 2016-08-16 08:30  孤松伴月  阅读(5924)  评论(0编辑  收藏  举报