当前位置: 首页>>代码示例>>C#>>正文


C# UdpClient.ReceiveAsync方法代码示例

本文整理汇总了C#中System.Net.Sockets.UdpClient.ReceiveAsync方法的典型用法代码示例。如果您正苦于以下问题:C# UdpClient.ReceiveAsync方法的具体用法?C# UdpClient.ReceiveAsync怎么用?C# UdpClient.ReceiveAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Sockets.UdpClient的用法示例。


在下文中一共展示了UdpClient.ReceiveAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ReceiveAndCheckAsync

 private static async Task ReceiveAndCheckAsync(UdpClient client, string expectedMessage)
 {
         var incomingBytes = new List<byte>();
     var connectionReset=false;
     try
     {
         do
         {
             var udpReceiveResult = await client.ReceiveAsync();
             incomingBytes.AddRange(udpReceiveResult.Buffer);
         } while (TcpMessenger.IsReadingShouldContinue(incomingBytes));
     }
     catch (SocketException ex)
     {
         if (ex.SocketErrorCode == SocketError.ConnectionReset)
         {
             connectionReset = true;
         }
     }
     var actual = Encoding.UTF8.GetString(incomingBytes.ToArray());
     if (connectionReset)
     {
         TcpMessenger.ErrorConnectionReset(actual);
     }
     else if (actual != expectedMessage)
     {
         TcpMessenger.ErrorWrongMessage(actual);
     }
 }
开发者ID:axxeny,项目名称:ServerEfficiencyTest,代码行数:29,代码来源:UdpConsumer.cs

示例2: BeginListeningAsync

		public async Task BeginListeningAsync (CancellationToken token)
		{
			var client = new UdpClient (BroadcastEndpoint);
			client.JoinMulticastGroup (BroadcastEndpoint.Address);
			token.Register (() => client.Close ());

			while (true) {
				token.ThrowIfCancellationRequested ();
				try {
					var result = await client.ReceiveAsync ();
					var data = Encoding.UTF8.GetString (result.Buffer);
					if (data.StartsWith (Header, StringComparison.Ordinal)) {
						if (ServerFound != null) {
							var details = new ServerDetails {
								Hostname = result.RemoteEndPoint.Address.ToString (),
								Port = int.Parse (data.Substring (Header.Length))
							};
							LoggingService.LogInfo ("Found TunezServer at {0}", details.FullAddress);
							ServerFound (this, details);
						}
					}
				} catch (ObjectDisposedException) {
					token.ThrowIfCancellationRequested ();
					throw;
				} catch (SocketException) {
					token.ThrowIfCancellationRequested ();
					// Ignore this
				} catch (Exception ex) {
					token.ThrowIfCancellationRequested ();
					LoggingService.LogInfo ("Ignoring bad UDP {0}", ex);
				}
			}
		}
开发者ID:alanmcgovern,项目名称:tunez,代码行数:33,代码来源:UdpBroadcast.cs

示例3: ReaderAsync

        private static async Task ReaderAsync(int port, string groupAddress)
        {
            using (var client = new UdpClient(port))
            {
                if (groupAddress != null)
                {
                    client.JoinMulticastGroup(IPAddress.Parse(groupAddress));
                    WriteLine($"joining the multicast group {IPAddress.Parse(groupAddress)}");
                }

                bool completed = false;
                do
                {
                    WriteLine("starting the receiver");
                    UdpReceiveResult result = await client.ReceiveAsync();
                    byte[] datagram = result.Buffer;
                    string received = Encoding.UTF8.GetString(datagram);
                    WriteLine($"received {received}");
                    if (received == "bye")
                    {
                        completed = true;
                    }
                } while (!completed);
                WriteLine("receiver closing");

                if (groupAddress != null)
                {
                    client.DropMulticastGroup(IPAddress.Parse(groupAddress));
                }
            }
        }
开发者ID:ProfessionalCSharp,项目名称:ProfessionalCSharp6,代码行数:31,代码来源:Program.cs

示例4: Receive

 private void Receive(UdpClient udpClient)
 {
     udpClient.ReceiveAsync().ContinueWith(res =>
     {
         if (DataReceived != null)
             DataReceived(res.Result.RemoteEndPoint, CommandBase.Parse(res.Result.Buffer));
         Receive(udpClient);
     });
 }
开发者ID:kalantyr,项目名称:Parallel,代码行数:9,代码来源:Connector.cs

示例5: StartUdpServer

        private async void StartUdpServer()
        {
            var endPoint = new IPEndPoint(IPAddress.Any, 0);
            var udp = new UdpClient(8080);

            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<LogMessageHub>();

            while (true)
            {
                UdpReceiveResult received = await udp.ReceiveAsync();

                //TODO: Are we still listening for UDP messages at this point?

                var buffer = received.Buffer;

                var xmlText = Encoding.UTF8.GetString(buffer);
                var logEvent = new LogEvent();
                logEvent.PopulateFromLog4JXml(xmlText);

                var json = logEvent.ToJson();

                //This should be in the hub wrapper
                var applicationId = logEvent.ApplicationId;
                if (applicationId != null)
                    context.Clients.Group(applicationId).newLogMessage(json);
            }
        }
开发者ID:ytechie,项目名称:log4stuff,代码行数:27,代码来源:Global.asax.cs

示例6: Start

 public static async Task Start()
 {
     var client = new UdpClient(1812);
     var serializer = new RadiusPacketSerializer();
     while (true)
     {
         try
         {
             var result = await client.ReceiveAsync();
             var request = serializer.Read(result.Buffer);
             Console.WriteLine(request.Dump());
             if (request.Code == RadiusPacketCode.AccessRequest)
             {
                 var password = (RadiusBinaryAttribute)request.Attributes.FirstOrDefault(a => a.Type == RadiusAttributeType.UserPassword);
                 var code = ((password == null) || (string.Compare(RadiusPacketSerializer.DecodePassword(Secret, request.Authenticator, password.Value), Password, StringComparison.InvariantCulture) != 0))
                     ? RadiusPacketCode.AccessReject
                     : RadiusPacketCode.AccessAccept;
                 var response = new RadiusPacket
                 {
                     Code = code,
                     Identifier = request.Identifier,
                     Authenticator = request.Authenticator
                 };
                 var buffer = serializer.Write(response);
                 await client.SendAsync(buffer, buffer.Length, result.RemoteEndPoint);
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex);
         }
     }
 }
开发者ID:rupertbenbrook,项目名称:RadiusProtocol,代码行数:33,代码来源:Program.cs

示例7: GetServers

        public async Task<IEnumerable<Server>> GetServers(
            MasterServerRegion region = MasterServerRegion.All,
            params MasterServerFilter[] masterServerFilters)
        {
            var servers = new List<Server>();

            using (var client = new UdpClient(new IPEndPoint(IPAddress.Any, 0)))
            {
                client.Connect(_steamSteamIpAddress, _steamSteamPort);

                string thisServer = null;
                while (thisServer != FIRST_AND_LAST_SERVER)
                {
                    var requestPacket = CreateRequestPacket(thisServer ?? FIRST_AND_LAST_SERVER, region, masterServerFilters);
                    await client.SendAsync(requestPacket, requestPacket.Length);
                    var response = await client.ReceiveAsync();
                    var responseData = response.Buffer.ToList();
                    for (int i = HEADER_BYTES_LENGTH; i < responseData.Count; i++)
                    {
                        var ip = string.Join(".", responseData.GetRange(i, 4).ToArray());
                        int port = responseData[i + 4] << 8 | responseData[i + 5];
                        thisServer = string.Format("{0}:{1}", ip, port);
                        if (thisServer != FIRST_AND_LAST_SERVER)
                        {
                            servers.Add(new Server(new IPEndPoint(IPAddress.Parse(ip), port)));
                        }
                        i += 5;
                    }
                }
            }

            return servers;
        }
开发者ID:griha41,项目名称:Steam.Query,代码行数:33,代码来源:MasterServer.cs

示例8: ReceiveBufferReaderAsync

        public static async Task<BufferReader> ReceiveBufferReaderAsync(UdpClient client, int headerSize)
        {
            var response = await client.ReceiveAsync();
            var reader = new BufferReader(response.Buffer);
            reader.Skip(headerSize);

            return reader;
        }
开发者ID:robhol,项目名称:Steam.Query,代码行数:8,代码来源:SteamAgent.cs

示例9: receiveBytesAsync

 public async Task<byte[]> receiveBytesAsync(int port)
 {
     UdpClient trasport = new UdpClient(port);
    // IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
     UdpReceiveResult result = await trasport.ReceiveAsync();
     byte[] bytes = result.Buffer;
     trasport.Close();
     return bytes;
 }
开发者ID:gontcaliuba,项目名称:Broker,代码行数:9,代码来源:MessageSenderReceiver.cs

示例10: GetServerRules

 public async Task<ServerRulesResult> GetServerRules()
 {
     using (var client = new UdpClient(new IPEndPoint(IPAddress.Any, 0)))
     {
         client.Connect(EndPoint);
         var requestPacket = new List<byte>();
         requestPacket.AddRange(new Byte[] {0xFF, 0xFF, 0xFF, 0xFF, 0x56});
         requestPacket.AddRange(BitConverter.GetBytes(-1));
         await client.SendAsync(requestPacket.ToArray(), requestPacket.ToArray().Length);
         UdpReceiveResult response = await client.ReceiveAsync();
         List<byte> responseData = response.Buffer.ToList();
         requestPacket.Clear();
         requestPacket.AddRange(new Byte[] {0xFF, 0xFF, 0xFF, 0xFF, 0x56});
         requestPacket.AddRange(responseData.GetRange(5, 4));
         await client.SendAsync(requestPacket.ToArray(), requestPacket.ToArray().Length);
         response = await client.ReceiveAsync();
         return ServerRulesResult.Parse(response.Buffer);
     }
 }
开发者ID:griha41,项目名称:Steam.Query,代码行数:19,代码来源:Server.cs

示例11: ReceiveDataAsync

        private async Task<ReceiveDataInfo> ReceiveDataAsync(ServerAddress address, byte[] data, CancellationToken ct, params char[] header)
        {
            var udpClient = new UdpClient();
            var ipAddr = IPAddress.Parse(address.Ip);
            try
            {
                udpClient.Connect(ipAddr, address.Port);

                var sendTime = DateTime.Now;
                await udpClient.SendAsync(data, data.Length);

                Packet packet = null;            
                return await Task.Run(async () =>
                {
                    while (true)
                    {
                        var clientResult = await udpClient.ReceiveAsync().WithCancellation(ct);
                        var remoteIp = clientResult.RemoteEndPoint.Address.ToString();
                        var remotePort = clientResult.RemoteEndPoint.Port;
                        var receiveDate = DateTime.Now;
                        var packetReader = new PacketReader(clientResult.Buffer);
                        var packetheader = packetReader.ReadLong();
                        if (packet == null)
                        {
                            packet = engineFactory.CreatePacket(packetheader);
                        }
                        packet.AddData(clientResult.Buffer);
                        if (packet.IsCompleted)
                        {
                            var messageReader = new PacketReader(packet.Payload);
                            var messageheader = messageReader.ReadByte();
                            var messageHeaderChar = Convert.ToChar(messageheader);
                            if (header.Contains(messageHeaderChar))
                            {
                                var result = new ReceiveDataInfo
                                {
                                    Ping = (int)(DateTime.Now - sendTime).TotalMilliseconds,
                                    Data = packet.Payload,
                                    MessageHeaderChar = messageHeaderChar,
                                };
                                return result;
                            }
                        }
                    }
                });
            }
            catch 
            {
                throw new OperationCanceledException();
            }
            finally
            {
                udpClient.Close();
            }
        }
开发者ID:AlexSbyshko,项目名称:Barsik,代码行数:55,代码来源:UDPRequester.cs

示例12: udpReceiveAsync

        protected async void udpReceiveAsync(int port, HandleMessage handleMessage)
        {
            IPEndPoint remoteIP = new IPEndPoint(IPAddress.Any, port);
            UdpClient udpClient = new UdpClient(remoteIP);

            while (true)
            {
                UdpReceiveResult rst = await udpClient.ReceiveAsync();
                handleMessage(Encoding.ASCII.GetString(rst.Buffer), rst.RemoteEndPoint.Address);
            }
        }
开发者ID:864668723,项目名称:128,代码行数:11,代码来源:FileTransferForm.cs

示例13: ServeAsync

        public static async Task ServeAsync(UdpClient server)
        {
            IDictionary<IPEndPoint, List<byte>> received=new Dictionary<IPEndPoint, List<byte>>();

            var sendTasks = new List<Task>();
            while (_sent < Constants.ClientCount)
            {
                await server.ReceiveAsync()
                    .ContinueWith(udpReceivedResult => sendTasks.Add(AddReceivedToDicAndSendIfShouldAsync(server, udpReceivedResult.Result, received)));
            }
            await Task.WhenAll(sendTasks);
        }
开发者ID:axxeny,项目名称:ServerEfficiencyTest,代码行数:12,代码来源:UdpServer.cs

示例14: SendToClientFileAsync

        /// <summary>
        /// 向客户端异步发送文件
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="filePath"></param>
        public async Task SendToClientFileAsync(string ip, int port, string filePath, Message msg)
        {
            // 新建 Udp 用于发送文件
            var sendClient = new UdpClient();

            try
            {
                FileInfo fileInfo = new FileInfo(filePath);
                msg.Type = MessageEnum.FILE;  // 设置发送文件标识
                msg.FileLength = fileInfo.Length;

                msg.FileName = Regex.Match(filePath, @"\\([^\\]+\.[^\\]+)").Groups[1].Value;  // 获取文件名

                byte[] datagram = Encoding.Unicode.GetBytes(JsonConvert.SerializeObject(msg));
                IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), port);

                /*
                 * 向‘原’远程客户端发送请求传送文件的请求,
                 * 接收‘新’远程客户端的响应,获取传送文件的端口
                 * 
                 * 注:原远程客户端用于发送消息,新远程客户端用于发送文件
                 */
                await sendClient.SendAsync(datagram, datagram.Length, endPoint);

                //IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                UdpReceiveResult result = await sendClient.ReceiveAsync().ConfigureAwait(false);   // 阻塞直到接收到远程客户端的响应

                /*
                 * 开始发送文件
                 */
                byte[] buffer = new byte[MAXSIZE];
                using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 1, true))
                {
                    int percent = 0;
                    int count = 0;
                    while ((count = await fs.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0)
                    {
                        //await Task.Delay(10);
                        await sendClient.SendAsync(buffer, count, result.RemoteEndPoint);

                        if (Client.SendFileProgressNotify != null)
                        {
                            Client.SendFileProgressNotify(String.Format("{0:F2}%", (percent += count) / msg.FileLength * 100));
                        }
                    }
                    sendClient.Close();
                }
            }
            catch (Exception e)
            {
                Log.Write(e.Message);
            }
        }
开发者ID:KanLei,项目名称:UdpAndTcp,代码行数:59,代码来源:ProcessFileByUdp.cs

示例15: ServerAsync

    static async Task ServerAsync(CancellationToken ct)
    {
      throw new ApplicationException("died");

      var client = new UdpClient(5555);

      var request = new byte[0];

      while (!ct.IsCancellationRequested)
      {
        await client.SendAsync(request, request.Length);
        var response = await client.ReceiveAsync();
      }
    }
开发者ID:stormcrow79,项目名称:FrameworkTests,代码行数:14,代码来源:Program.cs


注:本文中的System.Net.Sockets.UdpClient.ReceiveAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。