C# UDP 侦听器解除阻塞?或防止接收卡住 [英] C# UDP listener un-blocking? or prevent revceiving from being stuck

查看:109
本文介绍了C# UDP 侦听器解除阻塞?或防止接收卡住的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在这里寻找像我这样的以前的问题,但似乎找不到我需要的答案.

I've been searching for previous problems like mine here but it seems I can't find the answer I need.

我的目标是防止我的 UDP 侦听器不挂起.我有一个 UDP 侦听器,它等待消息,但如果没有接收到消息,它就挂在那里.

My goal is to prevent my UDP listener from not hanging. I have a UDP listener who waits for messages but if there is nothing to receive it just hangs there.

我已经阅读了其他线程,他们说我需要将 Blocking 设置为 false,但我找不到如何设置它.抱歉,我刚接触 C# 和套接字编程.

I have read other threads and they say that I need to set the Blocking to false but I can't find how to set it. Sorry I'm just new to C# and to socket programming.

这是我的听众的部分:

while (true)
{
    try
    {
        byte[] data = listener.Receive(ref groupEP);

        IPEndPoint newuser = new IPEndPoint(groupEP.Address, groupEP.Port);
        string sData =  (System.Text.Encoding.ASCII.GetString(data));

    }
    catch (Exception e)
    {
    }
}

我的问题是它只是在以下行冻结:

My problem is it just freezes on the following line:

byte[] data = listener.Receive(ref groupEP);

推荐答案

使用 UDPClient 上的可用属性(如果这是您正在使用的)来确定网络队列中是否有要读取的数据.

Use the available property on the UDPClient (if this is what you are using) to determine if you have data in the network queue to read.

while (true)
{
    try
    {
        if (listener.Available > 0) // Only read if we have some data 
        {                           // queued in the network buffer. 
            byte[] data = listener.Receive(ref groupEP);

            IPEndPoint newuser = new IPEndPoint(groupEP.Address, groupEP.Port);
            string sData =  (System.Text.Encoding.ASCII.GetString(data));
        }
    }
    catch (Exception e)
    {
    }
}

这篇关于C# UDP 侦听器解除阻塞?或防止接收卡住的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆