Socket.Poll()

本文详细介绍了Socket的Poll方法,包括参数解读和模式选择。通过实例展示了如何使用Poll检查Socket的读写状态和错误情况。Poll方法允许在指定微秒时间内或无限期等待Socket的状态改变,对于高效处理网络通信具有重要意义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

此外,poll()方法是一种效率很高的方法,当数据很少或为零时,其返回的速度十分快.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值