C#中UdpClient无法接收数据

流苏晚晴 流苏晚晴 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
用C#写了个UDP程序,但是发现接收的时候一直被阻塞,我用的是同步接收,简单的用了一个while(TRUE)循环接收数据。但是在RecvClient.Receive(ref RemoteEndPoint)这个地方就不动了?下面贴上代码
public void RecieveData()
{
IPAddress locip = IPAddress.Parse(LocalIp);
//IPEndPoint locEndPort = new IPEndPoint(locip, LocalPort);
IPEndPoint locEndPort = new IPEndPoint(locip, SendToPort);
if (RecvClient == null)
{
RecvClient = new UdpClient(locEndPort);
RecvClient.Client.ReceiveTimeout = 60000;
RecvClient.Connect(IPAddress.Parse(SendToIp), SendToPort);
}

Thread RecvThread = new Thread(ReceiveMessage);
RecvThread.Start();
}


private void ReceiveMessage()
{
IPEndPoint RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
//RemoteEndPoint = new IPEndPoint(IPAddress.Parse(LocalIp), SendToPort);
while (true)
{
try
{
//关闭UDPRecvClient会引发异常
byte[] receiveBytes = RecvClient.Receive(ref RemoteEndPoint);

string msg = Encoding.Unicode.GetString(receiveBytes);
string ShowMsg = RemoteEndPoint.ToString() + ":" + msg;
//消息容器添加加锁,防止容器信息出错
//lock (lockObj)
//{
// listMsg.Add(ShowMsg);
//}
if (msg == SendMsgs)
{
IsOperateSuccess = true;
}
}
catch
{
break;
}
}
}


请问是我还有哪些地方没有考虑到吗?
...全文
评论 8
收藏 已收藏
分享
返回顶部
流苏晚晴
C# 111,129 成员 642,539 内容