Exemple #1
0
        /// <summary>
        ///
        /// </summary>
        public void StartReceiving()
        {
            _receiveBuffer = "";
            AsyncCallback callback = new AsyncCallback(ReceiveCallBack);

            _udp.BeginReceive(callback, _udp);
            IsAlive       = true;
            IsTerminating = false;
        }
Exemple #2
0
        private void Close()
        {
            if (m_shared_conn != null)
            {
                m_shared_conn.BeginReceive(OnReceiveData, m_shared_conn);
            }

            if (m_exclusive_conn != null)
            {
                m_exclusive_conn.BeginReceive(OnReceiveData, m_exclusive_conn);
            }
        }
Exemple #3
0
        /// <summary>
        /// 运行程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (button1.Content.ToString() == "停止运行")
            {
                foreach (var item in states)
                {
                    //释放内存
                    ((Timer)item.UserToKen).Dispose();
                    if (!item.CurrentProcess.HasExited)
                    {
                        item.CurrentProcess.Kill();
                    }
                }
                try
                {
                    //移除组播
                    udp.DropMulticastGroup(System.Diagnostics.UDPGroup.group.ep.Address);
                    udp.Close();

                    states.Clear();
                    task.Dispose();
                }
                catch (Exception ex)
                {
                }
                button1.Content = "开始运行";
            }
            else
            {
                //当前已经采集的索引
                if (System.IO.File.Exists(ProgressFileName))
                {
                    List <string> arr = System.IO.File.ReadLines(ProgressFileName).ToList();
                    foreach (var item in Strs)
                    {
                        //得到当前项的状态如果包含则将当前项设置为 true 表示已经处理过了
                        if (arr.Contains(item.Key))
                        {
                            item.Value.IsCollectioned = true;
                        }
                    }
                }
                //初始化采集进程
                System.Linq.Enumerable.Range(0, MaxPorcess).ToList().ForEach((p) =>
                {
                    System.Threading.Thread.Sleep(40);
                    AddStates();
                });


                //开始监听
                task = System.Threading.Tasks.Task.Factory.StartNew(() =>
                {
                    udp = new System.Net.Sockets.UdpClient(System.Diagnostics.UDPGroup.group.ep.Port);
                    udp.JoinMulticastGroup(System.Diagnostics.UDPGroup.group.ep.Address);
                    udp.BeginReceive(AsyncCallback, udp);
                });
                button1.Content = "停止运行";
            }
        }
 //アクセス要求
 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);
     }
 }
 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);
 }
Exemple #6
0
        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);
        }
 public UDPServer(IEnumerable <int> listenPorts)
 {
     foreach (var port in listenPorts)
     {
         var udpClient = new System.Net.Sockets.UdpClient();
         udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, port));
         udpClient.BeginReceive(Receive, udpClient);
     }
 }
        /// <summary>
        /// Starts listening for incoming connections
        /// </summary>
        public override void Start()
        {
            if (Running)
                return;

            //TODO test if it is better to use socket directly
            //Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            
            listener = new System.Net.Sockets.UdpClient(endpoint.Port);
            listener.BeginReceive(new AsyncCallback(ReceiveData), listener);
        }
Exemple #9
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);
            }
        }
Exemple #10
0
        private void BeginReceiveTask(string comPort)
        {
            Task.Run(() =>
            {
                System.Net.IPEndPoint connectIP = new System.Net.IPEndPoint(
                    IPAddress.Any,
                    int.Parse(comPort));

                UdpClient = new System.Net.Sockets.UdpClient(connectIP);
                UdpClient.BeginReceive(Receive, UdpClient);
            });
        }
Exemple #11
0
        /// <summary>
        /// Starts listening for incoming connections
        /// </summary>
        public override void Start()
        {
            if (Running)
            {
                return;
            }

            //TODO test if it is better to use socket directly
            //Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            listener = new System.Net.Sockets.UdpClient(endpoint.Port);
            listener.BeginReceive(new AsyncCallback(ReceiveData), listener);
        }
Exemple #12
0
        public void Start()
        {
            Open();

            if (m_shared_conn != null)
            {
                m_shared_conn.BeginReceive(OnReceiveData, m_shared_conn);
            }

            if (m_exclusive_conn != null)
            {
                m_exclusive_conn.BeginReceive(OnReceiveData, m_exclusive_conn);
            }
        }
Exemple #13
0
        private void Form1_Load(object sender, EventArgs e)
        {
            // ソケット生成
            udpc  = new System.Net.Sockets.UdpClient(mmFsiUdpPortKV1000SpCam2);
            udpc2 = new System.Net.Sockets.UdpClient(mmFsiUdpPortKV1000SpCam2s);
            // ソケット非同期受信(System.AsyncCallback)
            udpc.BeginReceive(ReceiveCallback, udpc);

            timeBeginPeriod(time_period);

            string   s       = "KV1000SpCam_log1_" + DateTime.Today.ToString("dd") + ".txt";
            Encoding sjisEnc = Encoding.GetEncoding("Shift_JIS");

            writer = new StreamWriter(@"E:\log\" + s, true, sjisEnc);
        }
Exemple #14
0
        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}");
            }
        }
Exemple #15
0
        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);
                }
            }
        }
Exemple #16
0
        private void xInitUdp()
        {
            int portno = 4126;

            if (udpClient != null)
            {
                return;
            }

            //UdpClientを作成し、指定したポート番号にバインドする
            System.Net.IPEndPoint localEP = new System.Net.IPEndPoint(System.Net.IPAddress.Any, portno);

            udpClient = new System.Net.Sockets.UdpClient(localEP);
            //非同期的なデータ受信を開始する
            udpClient.BeginReceive(ReceiveCallback, udpClient);
            xLog("udp open. port=" + portno);
        }
        IEnumerator receive_loop()
        {
            var e = new System.Net.IPEndPoint(System.Net.IPAddress.Any, listenPort);
            var u = new System.Net.Sockets.UdpClient(e);

            u.EnableBroadcast = true;
            var s = new UdpState();

            s.e = e;
            s.u = u;
            for (; ;)
            {
                received = false;
                u.BeginReceive(new System.AsyncCallback(ReceiveCallback), s);
                while (!received)
                {
                    yield return(null);
                }
            }
        }
Exemple #18
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);
        }
Exemple #19
0
        //接続してからの処理
        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);
        }
Exemple #20
0
 public void Launch()
 {
     if (socket != null)
     {
         return;
     }
     try
     {
         dataPacker = new DataPacker();
         IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, port);
         socket = new System.Net.Sockets.UdpClient(endPoint);
         socket.EnableBroadcast = true;
         socket.BeginReceive(ReceiveResult, socket);
         IsActive = true;
         Debug.Log("主机初始化成功");
     }
     catch (Exception e)
     {
         Debug.Log(e);
     }
 }
Exemple #21
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);
        }
Exemple #22
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);
                }
            }
        }
Exemple #23
0
 private void ListenForNextMessage()
 {
     udpClient.BeginReceive(OnMessageReceived, null);
 }
Exemple #24
0
        private void xInitUdp()
        {
            int portno = 4126;
            if (udpClient != null)
            {
                return;
            }

            //UdpClientを作成し、指定したポート番号にバインドする
            System.Net.IPEndPoint localEP = new System.Net.IPEndPoint(System.Net.IPAddress.Any, portno);

            udpClient = new System.Net.Sockets.UdpClient(localEP);
            //非同期的なデータ受信を開始する
            udpClient.BeginReceive(ReceiveCallback, udpClient);
            xLog("udp open. port="+portno);
        }
Exemple #25
0
 public void Initialize(int port)
 {
     udpClient = new System.Net.Sockets.UdpClient(port);
     udpClient.BeginReceive(OnConnection, null);
 }