示例#1
0
        //データを受信した時
        private void ReceiveCallback(IAsyncResult ar)
        {
            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("Error({0}/{1})",
                                  ex.Message, ex.ErrorCode);
                return;
            }
            catch (ObjectDisposedException ex)
            {
                //すでに閉じている時は終了
                Console.WriteLine("Socket closed");
                return;
            }

            //データを文字列に変換する
            string rcvMsg = System.Text.Encoding.UTF8.GetString(rcvBytes);
            var    e      = new UDP_ReceiveData(rcvMsg, remoteEP.Address.ToString());

            Console.WriteLine("datarecived:{0}", rcvMsg);
            packet_receive(this, e);

            //再びデータ受信を開始する
            udp.BeginReceive(ReceiveCallback, udp);
        }
示例#2
0
        public async Task ListenMessage()
        {
            //var remote = new IPEndPoint(IPAddress.Any, port);
            //client.Connect(remote);
            //client.BeginReceive(ReceiveCallback, client);
            //return Task.Run(() =>
            //{
            while (true)
            {
                Console.WriteLine("start_listen:port:{0}", port);
                var remote  = new IPEndPoint(IPAddress.Any, port);
                var receive = await client.ReceiveAsync();

                //var receive = client.Receive(ref remote);
                //var str = Encoding.UTF8.GetString(receive);
                var str = Encoding.UTF8.GetString(receive.Buffer);

                var e = new UDP_ReceiveData(str, receive.RemoteEndPoint.Address.ToString());
                //var e = new UDP_ReceiveData(str, remote.Address.ToString());
                packet_receive(this, e);
            }
            // });
        }