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

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");
}
}
}
好吧,我已经解决了,用异步模式即可。 谁随便回答下吧,我就给分

第1个回答  2019-08-12
能详细说一下怎么解决吗
第2个回答  2014-04-24
原因是有些资源没有释放把追问

我都在下面补充了,说了是采用异步接收就OK了,你还误导别人..... 好吧,你回答了 分给你

本回答被提问者采纳
相似回答