Unity - A计划(永久有效期) 扫二维码继续学习 二维码时效为半小时

(196评价)
价格: 4039.00元
关于UdpClient接收的问题。
sdhexu发起了话题2017-08-08
0
回复
634
浏览

我要做一个局域网游戏,类似CS创建房间的那种,所以,需要服务端不停的广播自己的IP、房间名称等信息。客户端收到之后,就会将房间显示出来。

现在有一个问题,当我启动了监听之后,(服务端没有启动,没有收到任何消息呢)再停止游戏时,unity就会无响应,一直卡在那里关不掉,非得在任务管理器里强制结束unity....

public class ServerList : MonoBehaviour
{
    protected Transform m_ServerListGrid;  // UI Grid 组件,用来显示房间的容器
    protected Dictionary<string, ServerItem> m_ServerDict;   // 所有的房间列表
    protected bool m_bStartListen = false;      // 是否开始监听
    protected Thread m_ListenThread = null;     // 开始监听的线程
    [SerializeField]
    [Range(7903, 65500)]
    protected int m_Port = 7903;          // 监听端口
    [SerializeField]
    protected GameObject m_ServerItemPrefab; // 房间prefab

    private void Awake()
    {
        m_ServerDict = new Dictionary<string, ServerItem>();
        m_ServerListGrid = transform.Find("Scroll/Grid");

        if( m_ListenThread == null && m_bStartListen == false )
            StartListen();  // 只要这里启动起来,再关UNITY就会出问题,注视掉这句,就没问题了。
    }

    public void StartListen()
    {
        if (m_ListenThread == null)
        {
            m_bStartListen = true;
            m_ListenThread = new Thread(new ThreadStart(RecvUDPMsg));
            m_ListenThread.IsBackground = true;
            m_ListenThread.Start();
        }
    }

    private void RecvUDPMsg()  // 接收消息的线程
    {
        UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Any, m_Port));
        IPEndPoint ep = new IPEndPoint(IPAddress.Any, 0);
        while ( m_bStartListen )
        {
            byte[] buff = client.Receive(ref ep);
            GameRoom gr = GameRoom.CreateFromSerial(buff);
            string key = gr.ServerIP + ":" + gr.ServerPort.ToString();
            if (m_ServerDict.ContainsKey(key))
            {
                ServerItem si = m_ServerDict[key];
                si.SetGameRoomInfo(gr);
            }
            else
            {
                GameObject obj = GameObject.Instantiate(m_ServerItemPrefab, m_ServerListGrid, true);
                ServerItem si = obj.GetComponent<ServerItem>();
                si.SetGameRoomInfo(gr);
                m_ServerDict.Add(key, si);
            }
        }
        client.Close();
    }
    [HideInInspector]
    public ServerItem m_CurrentSelected = null;   // 当前选择的房间

    private void OnDestroy()  // 这里根本就运行不到
    {
        print("Destroy");  // 显示不出来。。。就卡死了。
        if (m_ListenThread != null)
        {
            m_bStartListen = false;
            while (m_ListenThread.IsAlive)
                Thread.Sleep(10);
        }
    }

    private void OnDisable()
    {
        print("Desable");   // 这里也显示不出来。卡死了。
        if (m_ListenThread != null)
        {
            m_bStartListen = false;
            while (m_ListenThread.IsAlive)
                Thread.Sleep(10);
        }
    }
}

 

 

发表回复
你还没有登录,请先 登录或 注册!