コード例 #1
0
ファイル: UDP.cs プロジェクト: YusukeKajita/ShadowMediaSystem
 //アクセス要求
 void AccessReceiveCallback(IAsyncResult ar)
 {
     Console.WriteLine("rec:c");
     //受信中止
     System.Net.Sockets.UdpClient client   = (System.Net.Sockets.UdpClient)ar.AsyncState;
     System.Net.IPEndPoint        remoteEP = null;
     byte[] recieveData;
     try
     {
         recieveData = client.EndReceive(ar, ref remoteEP);
         UDP_PACKETS_CODER.UDP_PACKETS_DECODER dec = new UDP_PACKETS_CODER.UDP_PACKETS_DECODER();
         dec.Source = recieveData;
         bool state = dec.get_bool();
         if (state)
         {
             //サーバーが返したポートに接続しなおし
             this.MakeNewClient(dec.get_int(), dec.get_int());
             this.IsAccessed = true;
         }
     }
     catch (Exception ex)
     {
         Console.Write(ex.Message);
         return;
     }
     //受信再開
     if (!this.IsAccessed)
     {
         client.BeginReceive(this.AccessReceiveCallback, client);
     }
 }
コード例 #2
0
ファイル: UDP.cs プロジェクト: YusukeKajita/ShadowMediaSystem
 void ReceiveCallback(IAsyncResult ar)
 {
     Console.WriteLine("rec:s");
     //受信中止
     System.Net.Sockets.UdpClient localClient = (System.Net.Sockets.UdpClient)ar.AsyncState;
     System.Net.IPEndPoint        remoteEP    = null;
     byte[] recieveData;
     try
     {
         recieveData = localClient.EndReceive(ar, ref remoteEP);
         UDP_PACKETS_CODER.UDP_PACKETS_DECODER dec = new UDP_PACKETS_CODER.UDP_PACKETS_DECODER();
         dec.Source = recieveData;
         if (dec.get_bool())
         {
             //アクセス要求が来たら返信
             this.MakeNewLocalClient(remoteEP);
         }
     }
     catch (Exception ex)
     {
         Console.Write(ex.Message);
         return;
     }
     //受信再開
     localClient.BeginReceive(ReceiveCallback, localClient);
 }
コード例 #3
0
ファイル: UdpClient.cs プロジェクト: 54369075/MiniFramework
        private void ReceiveResult(IAsyncResult ar)
        {
            socket = (System.Net.Sockets.UdpClient)ar.AsyncState;
            IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);

            recvBuffer = socket.EndReceive(ar, ref remote);
            dataPacker.UnPack(recvBuffer);
            socket.BeginReceive(ReceiveResult, socket);
        }
コード例 #4
0
        public void AsyncCallback(IAsyncResult ar)
        {
            System.Net.Sockets.UdpClient udp = (System.Net.Sockets.UdpClient)ar.AsyncState;
            //如果已经释放的资源
            if (udp.Client == null)
            {
                //直接返回
                return;
            }
            IPEndPoint remoteHost = null;

            if (ar.IsCompleted)
            {
                //当前客户端的UDP不能为null
                if (udp.Client != null)
                {
                    //接收数据
                    byte[] bytearr = new byte[0];
                    try
                    {
                        //接收数据
                        bytearr = udp.EndReceive(ar, ref remoteHost);
                    }
                    catch (ObjectDisposedException)
                    {
                        return;
                    }
                    String States = System.Text.Encoding.GetEncoding("GB2312").GetString(bytearr);
                    ///如果带|则表示当前是状态 x,y|状态说明
                    ////if (States.IndexOf("|") != -1)
                    //{
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        UpdateStates(States);
                    }));
                    //}
                    ///采集完成{0},{1}
                    if (States.IndexOf("状态:采集完成:") != -1)
                    {
                        System.IO.File.AppendAllLines(ProgressFileName, new string[] { States.Replace("采集完成", string.Empty) });
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            RemoveStates(States.Replace("状态:采集完成:", string.Empty));
                        }));
                    }
                }
            }
            //当前客户端的UDP不能为null
            if (udp.Client != null)
            {
                //重新开始收数据
                udp.BeginReceive(AsyncCallback, udp);
            }
        }
コード例 #5
0
        public static void ReceiveCallback(System.IAsyncResult ar)
        {
            System.Net.Sockets.UdpClient u = (System.Net.Sockets.UdpClient)((UdpState)(ar.AsyncState)).u;
            System.Net.IPEndPoint        e = (System.Net.IPEndPoint)((UdpState)(ar.AsyncState)).e;
            var receiveBytes  = u.EndReceive(ar, ref e);
            var receiveString = System.Text.Encoding.ASCII.GetString(receiveBytes);

            Debug.Log(string.Format("Received: {0}", receiveString)); // ここに任意の処理を書く

            received = true;

            actions.ForEach(action =>
            {
                action(receiveString);
            });
        }
コード例 #6
0
ファイル: UdpClient.cs プロジェクト: ProtoThis/among_us_clone
        private void OnConnection(IAsyncResult result)
        {
            try
            {
                IPEndPoint clientIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
                byte[]     data             = udpClient.EndReceive(result, ref clientIpEndPoint);

                // Start listening for the next client connection
                udpClient.BeginReceive(OnConnection, null);

                if (data.Length < sizeof(int))
                {
                    return;
                }

                Packet packet   = new Packet(data);
                int    playerId = packet.ReadInt();

                if (!playersManager.clients.ContainsKey(playerId))
                {
                    Logger.LogNotice(LoggerSection.Network, $"Skipping tcp packed from player {playerId}, because it is already disconnected");
                    return;
                }

                if (!playersManager.clients[playerId].IsConnectedViaUdp())
                {
                    playersManager.clients[playerId].ConnectUdp(clientIpEndPoint);
                    return;
                }

                if (!playersManager.clients[playerId].IsCorrectUdpIpEndPoint(clientIpEndPoint))
                {
                    Logger.LogError(LoggerSection.Network, "Hacking attempt, client ids doesn't match");
                    return;
                }

                HandlePacketData(playerId, packet);
            }
            catch (ObjectDisposedException objectDisposedException)
            {
                Logger.LogNotice(LoggerSection.Network, $"Error receiving UDP data because udpClient is already disposed: {objectDisposedException}");
            }
            catch (Exception exception)
            {
                Logger.LogError(LoggerSection.Network, $"Error receiving UDP data: {exception}");
            }
        }
コード例 #7
0
ファイル: UdpListener.cs プロジェクト: mkirov0/MultiPoolMiner
        private void ReceiveData(IAsyncResult ar)
        {
            try
            {
                System.Net.Sockets.UdpClient listener = (System.Net.Sockets.UdpClient)ar.AsyncState;
                byte[] data = listener.EndReceive(ar, ref endpoint);
                if (data.Length < 16)
                {
                    return;//bad request
                }
                UdpTrackerMessage request = UdpTrackerMessage.DecodeMessage(data, 0, data.Length, MessageType.Request);

                switch (request.Action)
                {
                case 0:
                    ReceiveConnect((ConnectMessage)request);
                    break;

                case 1:
                    ReceiveAnnounce((AnnounceMessage)request);
                    break;

                case 2:
                    ReceiveScrape((ScrapeMessage)request);
                    break;

                case 3:
                    ReceiveError((ErrorMessage)request);
                    break;

                default:
                    throw new ProtocolException(string.Format("Invalid udp message received: {0}", request.Action));
                }
            }
            catch (Exception e)
            {
                Logger.Log(null, e.ToString());
            }
            finally
            {
                if (Running)
                {
                    listener.BeginReceive(new AsyncCallback(ReceiveData), listener);
                }
            }
        }
コード例 #8
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            //UDP受信のコールバック
            //受信データをgQに入れる

            System.Net.Sockets.UdpClient udp = (System.Net.Sockets.UdpClient)ar.AsyncState;

            //非同期受信を終了する
            System.Net.IPEndPoint remoteEP = null;
            byte[] rcvBytes;
            try
            {
                rcvBytes = udp.EndReceive(ar, ref remoteEP);
            }
            catch (System.Net.Sockets.SocketException ex)
            {
                Console.WriteLine("受信エラー({0}/{1})",
                                  ex.Message, ex.ErrorCode);
                return;
            }
            catch (ObjectDisposedException ex)
            {
                //すでに閉じている時は終了
                Console.WriteLine("Socketは閉じられています。");
                return;
            }

            //データを文字列に変換し、キューに入れる
            string rcvMsg = System.Text.Encoding.UTF8.GetString(rcvBytes);

            rcvMsg.Replace("\n", " ").Replace("\r", "");
            //受信したデータをキューに入れる
            string displayMsg = string.Format("ip,{0},port,{1},msg,{2}", remoteEP.Address, remoteEP.Port, rcvMsg.Replace("\n", " ").Replace("\r", ""));

            //           textBox1.BeginInvoke(
            //               new Action<string>(AppendText), displayMsg);
            gQ.Enqueue(displayMsg);

            //再びデータ受信を開始する
            udp.BeginReceive(ReceiveCallback, udp);
        }
コード例 #9
0
        private void ReceiveCallBack(IAsyncResult res)
        {
            //if (!res.IsCompleted) return;
            byte[] data = _udp.EndReceive(res, ref _remoteEp);

            Encoding enc = Encoding.ASCII;
            string   str = enc.GetString(data);

            _receiveBuffer = str;   // no concatenation now
            ParseString(_receiveBuffer);

            if (!IsTerminating)
            {
                AsyncCallback callback = new AsyncCallback(ReceiveCallBack);
                _udp.BeginReceive(callback, _udp);
            }
            else
            {
                IsAlive = false;
            }
        }
コード例 #10
0
ファイル: UDP.cs プロジェクト: YusukeKajita/ShadowMediaSystem
        //接続してからの処理
        void ReceiveCallBack(IAsyncResult ar)
        {
            //受信中止
            System.Net.Sockets.UdpClient localClient = (System.Net.Sockets.UdpClient)ar.AsyncState;
            System.Net.IPEndPoint        remoteEP    = null;
            byte[] recieveData;
            try
            {
                recieveData = localClient.EndReceive(ar, ref remoteEP);
                //受信した時の処理
                this.DataReceived(ar, recieveData);
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                return;
            }

            //受信再開
            localClient.BeginReceive(this.ReceiveCallBack, localClient);
        }
コード例 #11
0
        private void Receive(IAsyncResult result)
        {
            System.Net.Sockets.UdpClient udp =
                (System.Net.Sockets.UdpClient)result.AsyncState;

            //非同期受信を終了する
            System.Net.IPEndPoint remoteIP = null;
            byte[] buf;

            try
            {
                buf = udp.EndReceive(result, ref remoteIP);
            }
            catch (System.Net.Sockets.SocketException ex)
            {
                Console.WriteLine("受信エラー({0}/{1})",
                                  ex.Message, ex.ErrorCode);
                return;
            }
            catch (ObjectDisposedException ex)
            {
                //すでに閉じている時は終了
                Console.WriteLine("Socketは閉じられています。" + ex.Message);
                return;
            }

            //データを文字列に変換する
            string Message = System.Text.Encoding.UTF8.GetString(buf);

            //受信したデータと送信者の情報をRichTextBoxに表示する
            string displayMsg = string.Format("[{0} ({1})] > {2}",
                                              remoteIP.Address, remoteIP.Port, Message);

            richTextBox1.BeginInvoke(
                new Action <string>(ShowMessage), displayMsg);

            //再びデータ受信を開始する
            udp.BeginReceive(Receive, udp);
        }
コード例 #12
0
        private void OnReceiveData(IAsyncResult asyncResult)
        {
            System.Net.Sockets.UdpClient conn = (System.Net.Sockets.UdpClient)asyncResult.AsyncState;
            try
            {
                System.Net.IPEndPoint ep = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0);
                byte[] local_buffer;
                int    rx = 0;

                try
                {
                    local_buffer = conn.EndReceive(asyncResult, ref ep);
                    rx           = local_buffer.Length;
                }
                catch (Exception) // ICMP port unreachable
                {
                    //restart data receive
                    conn.BeginReceive(OnReceiveData, conn);
                    return;
                }

                if (rx == 0)    // Empty frame : port scanner maybe
                {
                    //restart data receive
                    conn.BeginReceive(OnReceiveData, conn);
                    return;
                }

                try
                {
                    //verify message
                    BacnetAddress remote_address;
                    Convert((System.Net.IPEndPoint)ep, out remote_address);
                    BacnetBvlcV6Functions function;
                    int msg_length;
                    if (rx < BVLCV6.BVLC_HEADER_LENGTH - 3)
                    {
                        Trace.TraceWarning("Some garbage data got in");
                    }
                    else
                    {
                        // Basic Header lenght
                        int HEADER_LENGTH = bvlc.Decode(local_buffer, 0, out function, out msg_length, ep, remote_address);

                        if (HEADER_LENGTH == 0)
                        {
                            return;
                        }

                        if (HEADER_LENGTH == -1)
                        {
                            Trace.WriteLine("Unknow BVLC Header");
                            return;
                        }

                        // response to BVLC_REGISTER_FOREIGN_DEVICE (could be BVLC_DISTRIBUTE_BROADCAST_TO_NETWORK ... but we are not a BBMD, don't care)
                        if (function == BacnetBvlcV6Functions.BVLC_RESULT)
                        {
                            Trace.WriteLine("Receive Register as Foreign Device Response");
                        }

                        // a BVLC_FORWARDED_NPDU frame by a BBMD, change the remote_address to the original one (stored in the BVLC header)
                        // we don't care about the BBMD address
                        if (function == BacnetBvlcV6Functions.BVLC_FORWARDED_NPDU)
                        {
                            Array.Copy(local_buffer, 7, remote_address.adr, 0, 18);
                        }

                        if ((function == BacnetBvlcV6Functions.BVLC_ORIGINAL_UNICAST_NPDU) || (function == BacnetBvlcV6Functions.BVLC_ORIGINAL_BROADCAST_NPDU) || (function == BacnetBvlcV6Functions.BVLC_FORWARDED_NPDU))
                        {
                            //send to upper layers
                            if ((MessageRecieved != null) && (rx > HEADER_LENGTH))
                            {
                                MessageRecieved(this, local_buffer, HEADER_LENGTH, rx - HEADER_LENGTH, remote_address);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Exception in udp recieve: " + ex.Message);
                }
                finally
                {
                    //restart data receive
                    conn.BeginReceive(OnReceiveData, conn);
                }
            }
            catch (Exception ex)
            {
                //restart data receive
                if (conn.Client != null)
                {
                    Trace.TraceError("Exception in Ip OnRecieveData: " + ex.Message);
                    conn.BeginReceive(OnReceiveData, conn);
                }
            }
        }
コード例 #13
0
 private void OnMessageReceived(IAsyncResult result)
 {
     OnMessageReceivedSubject.OnNext(udpClient.EndReceive(result, ref ipEndpoint));
     ListenForNextMessage();
 }