中易网

C# 使用 UDPClient + 多线程 在程序关闭的时候程序无响应

答案:1  悬赏:10  
解决时间 2021-02-19 13:22
using UnityEngine;
using System.Collections;

using System;

using System.Text;

using System.Net;

using System.Net.Sockets;

using System.Threading;

public class TestUDPRcv : MonoBehaviour {

private UdpClient receiveUdpClient; //接收用
private const int port = 18001; //接收端端口
IPAddress ip; //本机IP
IPAddress remoteIp; //远程IP

string recvText = ""; //接收到的数据

// Use this for initialization
void Start () {

//获取本机可用IP地址
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
ip = ips[ips.Length - 1];
//为了在同一台机器调试,此IP也作为默认远程IP
remoteIp = ip;
LoadClient();

}

public void LoadClient()
{
//创建一个线程接收远程主机发来的信息
Thread myThread = new Thread(ReceiveData);
//将线程设为后台运行
myThread.IsBackground = true;
myThread.Start();
}

public void ReceiveData()
{

while (true)
{
//IPEndPoint local = new IPEndPoint(ip, port);
receiveUdpClient = new UdpClient(port);
try
{
//关闭udpClient时此句会产生异常
IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);
byte[] receiveBytes = receiveUdpClient.Receive(ref remote);
string returnData = Encoding.Unicode.GetString(receiveBytes);
Debug.Log(Encoding.Unicode.GetString(receiveBytes));
recvText = returnData.ToString();
Debug.Log("recvText:" + recvText);
receiveUdpClient.Close();
}
catch (Exception err)
{
// StopAsynchronousReceive();
// recvText = err.ToString();

Debug.Log("debug出错了");
print("print出错了啊");
receiveUdpClient.Close();
Console.WriteLine(err.Message);
break;
}
}
}

void OnGUI()
{
GUI.Label(new Rect(100,100,100,35),"收到的消息:");
recvText = GUI.TextField(new Rect(210, 100, 100, 35), recvText);
}

// Update is called once per frame
void Update () {
Debug.Log("recvText:" + recvText);
if (recvText == "Im a Test Message")
{
print("hello");
}
}
}

好吧,我已经解决了,用异步模式即可。 谁随便回答下吧,我就给分
最佳答案
原因是有些资源没有释放把
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
妻子诈骗的钱都用于还高利贷,判刑后丈夫负什
墨绿色的短裤可搭配哪些颜色的衣服
BONA咖啡厅我想知道这个在什么地方
08-11款新嘉年华 自动挡变速箱油 需要换什么
韩国牙膏进口报关关税多少 牙膏乇嗦
南中轴路/西刘路(路口)地址在什么地方,想过
企业网站宣传算广告范畴吗?
青岛裁缝店
七十除以五点六列竖式计算快快快即籍的
苹果6s电信卡能上网,为什么不能打电话?
鬼为什么会令人感到恐惧?
机箱电源温度多少合适?
153-x/10=189-x,X是多少?
利泰豪庭在什么地方啊,我要过去处理事情
澳洲净宗学院老师您好!请问澳洲图文巴建了一
推荐资讯
去北京旅游一礼拜,比较省的花1万块够花吗?
vocaloid的软件从网上下载后怎么安装
房产证上是小孩的名字2岁到时办房产证麻烦吗?
dtm哪个车队冠军最多??
48v电动车4个小电瓶,如果坏了两个小电瓶还能
bon-air的汉语意思
周杰伦的哪首歌每一句歌词的最后一个字都读翘
海尔bcd 235t 平均耗电量是多少
类似谢谢表示感谢的话
退休档案里学生表是67年身份证是66年其它的表
360随身wifi充电可以充一夜吗?
首邑上城在哪里啊,我有事要去这个地方
手机登qq时,显示手机磁盘不足,清理后重新登
刺客的套装怎么选啊?