Example #1
0
 public override void DisConnect(IPEndPoint iPEndPoint)
 {
     lock (ClientInstance)
     {
         string key = iPEndPoint.ToString();
         if (ClientInstance.TryGetValue(key, out Instance instance))
         {
             UDPInstance udpInstance = (UDPInstance)instance;
             udpInstance.Dispose();
             ClientInstance.Remove(key);
         }
     }
 }
Example #2
0
        private async Task <ReceiveResult> receiveAsync()
        {
            UdpReceiveResult receiveResult;

            receiveResult = await _udpClient.ReceiveAsync();

            //這個地方可以順便帶 device Id 如果發現有重複就應該擋掉
            var result = new ReceiveResult(receiveResult.RemoteEndPoint);

            if (ReqConnect.Length == receiveResult.Buffer.Length)
            {
                for (int i = 0; i < receiveResult.Buffer.Length; i++)
                {
                    result.IsOk = result.IsOk && receiveResult.Buffer[i].Equals(ReqConnect[i]);
                }
            }
            else
            {
                result.IsOk = false;
            }

            bool b = true;

            if (ReqDisconnect.Length == receiveResult.Buffer.Length)
            {
                for (int i = 0; i < receiveResult.Buffer.Length; i++)
                {
                    b = b && receiveResult.Buffer[i].Equals(ReqConnect[i]);
                }
            }
            if (!b)
            {
                DisConnect(receiveResult.RemoteEndPoint);
            }

            lock (ClientInstance)
            {
                if (ClientInstance.TryGetValue(receiveResult.RemoteEndPoint.ToString(), out Instance instance))
                {
                    UDPInstance udpInstance = (UDPInstance)instance;
                    udpInstance.PassData(receiveResult.Buffer);
                }
            }

            string clientIp = receiveResult.RemoteEndPoint.ToString();

            if (!ClientInstance.ContainsKey(clientIp) && result.IsOk)
            {
                // 建立玩家peer實體
                ClientNode  cNode    = _SocketServer.GetPeer(this, receiveResult.RemoteEndPoint, _SocketServer);
                UDPInstance instance = new UDPInstance(this, _udpClient, receiveResult.RemoteEndPoint, cNode);
                //註冊到 mListener 中,讓他的 Receive 功能能被叫
                ClientInstance.Add(clientIp, instance);
                //成功加入後傳送 Connect 事件給 Client
                await SendAsync(new byte[] { 1 }, cNode.IpEndPoint);

                cNode.Initialize();
            }

            return(result);
        }