关于udpclient接收时候假死的问题 5C

我用udpclient接收消息的时候,总是在Receive时候就卡着不动了,也用了线程,不知道是什么原因,哪位大神给我看看

//发送代码
UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Any, 0));
IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 1025);
byte[] buf = Encoding.Default.GetBytes("Are You Device?");

        try
        {
            client.Send(buf, buf.Length, endpoint);
            client.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

                    //接收按钮
                     private void button2_Click(object sender, EventArgs e)
    {
        Thread t = new Thread(new ThreadStart(RecvThread));
        t.Start();
        t.IsBackground = true;

    }

            //接收代码
             public void RecvThread()
    {
        while (true)
        {
            UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Any, 1025));
            IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0);
            try
            {
                byte[] buf = client.Receive(ref endpoint);
                string msg = Encoding.ASCII.GetString(buf);

                //string strReceive = string.Format((endpoint as IPEndPoint).Address.ToString() + ":" + (endpoint as IPEndPoint).Port.ToString());

                Console.WriteLine(msg.ToString());
                client.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

        }           

    }

3个回答

while循环里把接受数据改成这样:if(client.Available==0) continue; //没有数据,继续循环;有数据就接收 client.Receive(ref endpoint);

卡着不动有可能就是阻塞在Receive操作里面了吧,如果没有数据收到,并且socket是阻塞模式,就会卡在receive中。

helloworld_lan
helloworld_lan 那我要怎么解决啊
2 年多之前 回复

阻塞时接收, 卡死说明没有数据来, 应该是远端没数据过来

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐