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


C# UdpClient.SendAsync方法代码示例

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


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

示例1: 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

示例2: 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

示例3: 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

示例4: SendWakeOnLan

        private async Task SendWakeOnLan(string macAddress, IPEndPoint endPoint, CancellationToken cancellationToken)
        {
            const int payloadSize = 102;

            var macBytes = PhysicalAddress.Parse(macAddress).GetAddressBytes();
            _logger.Debug(String.Format("Sending magic packet to {0}", macAddress));

            // Construct magic packet
            var payload = new byte[payloadSize];
            Buffer.BlockCopy(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }, 0, payload, 0, 6);

            for (var i = 1; i < 17; i++) 
            { 
                Buffer.BlockCopy(macBytes, 0, payload, 6 * i, 6);
            }

            // Send packet LAN
            using (var udp = new UdpClient())
            {
                udp.Connect(endPoint);

                cancellationToken.ThrowIfCancellationRequested();

                await udp.SendAsync(payload, payloadSize).ConfigureAwait(false);
            }
        }
开发者ID:daltekkie,项目名称:Emby.ApiClient,代码行数:26,代码来源:NetworkConnection.cs

示例5: FindServers

        private async void FindServers(Action<ServerDiscoveryInfo> serverFound, Action<Exception> error, CancellationToken cancellationToken)
        {
            var serverIdsFound = new List<string>();

            // Create a udp client
            using (var client = new UdpClient(new IPEndPoint(IPAddress.Any, GetRandomUnusedPort())))
            {
                // Construct the message the server is expecting
                var bytes = Encoding.UTF8.GetBytes("who is EmbyServer?");

                // Send it - must be IPAddress.Broadcast, 7359
                var targetEndPoint = new IPEndPoint(IPAddress.Broadcast, 7359);

                try
                {
                    // Send the broadcast
                    await client.SendAsync(bytes, bytes.Length, targetEndPoint).ConfigureAwait(false);

                    while (!cancellationToken.IsCancellationRequested)
                    {
                        // Get a result back
                        var result = await client.ReceiveAsync().ConfigureAwait(false);

                        if (result.RemoteEndPoint.Port == targetEndPoint.Port)
                        {
                            // Convert bytes to text
                            var json = Encoding.UTF8.GetString(result.Buffer);

                            _logger.Debug("Received response from endpoint: " + result.RemoteEndPoint + ". Response: " + json);

                            if (!string.IsNullOrEmpty(json))
                            {
                                try
                                {
                                    var info = _jsonSerializer.DeserializeFromString<ServerDiscoveryInfo>(json);

                                    if (!serverIdsFound.Contains(info.Id))
                                    {
                                        serverIdsFound.Add(info.Id);
                                        info.EndpointAddress = result.RemoteEndPoint.Address.ToString();
                                        serverFound(info);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    _logger.ErrorException("Error parsing server discovery info", ex);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    error(ex);
                }
            }
        }
开发者ID:daltekkie,项目名称:Emby.ApiClient,代码行数:57,代码来源:ServerLocator.cs

示例6: 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

示例7: replyUdpAsync

 protected async Task replyUdpAsync(String replyMessage, IPAddress ip, int port)
 {
     UdpClient udpClient = new UdpClient();
     udpClient.MulticastLoopback = true;
     udpClient.ExclusiveAddressUse = false;
     
     byte[] bytes = Encoding.ASCII.GetBytes(replyMessage);
     await udpClient.SendAsync(bytes, bytes.Length, new IPEndPoint(ip, port));
     udpClient.Close();
 }
开发者ID:864668723,项目名称:128,代码行数:10,代码来源:FileTransferForm.cs

示例8: 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

示例9: GetParsedServers

        public async Task<List<IPEndPoint>> GetParsedServers(CancellationToken cancelToken, int limit = -1,
            IPEndPoint remote = null, int tried = -1) {
            var cur = -1;
            var servers = new List<IPEndPoint>();
            if (remote == null) {
                var hosts = await Dns.GetHostAddressesAsync("hl2master.steampowered.com").ConfigureAwait(false);
                if (tried == -1)
                    cur = new Random().Next(hosts.Length);
                else
                    cur = (tried + 1)%hosts.Length;
                var host = hosts[cur];
                const int port = 27011;

                remote = new IPEndPoint(host, port); //TODO: alternate ip and ports availability
            }
            var e = new IPEndPoint(IPAddress.Any, 0);
            var udpClient = new UdpClient(e) {
                Client = {ReceiveTimeout = Consts.DefaultReceiveTimeout, SendTimeout = Consts.DefaultSendTimeout }
            };

            var i = 0;
            const int maxIterations = 30;
            string lastSeed;
            var seed = "0.0.0.0:0";
            do {
                cancelToken.ThrowIfCancellationRequested();
                lastSeed = seed;
                var msg = BuildMessage(seed);

                if (await udpClient.SendAsync(msg, msg.Length, remote).ConfigureAwait(false) != msg.Length)
                    throw new Exception("Send failed.");
                byte[] response = null;
                var timedOut = false;
                try {
                    response =
                        (await
                                udpClient.ReceiveWithTimeoutAfter(Consts.DefaultReceiveTimeout, cancelToken).ConfigureAwait(false))
                            .Buffer;
                } catch (TimeoutException) {
                    timedOut = true;
                    if ((cur == -1) || (tried != -1) || (i != 0)) {
                        throw new TimeoutException(string.Format("Received timeout on try: {0} packet: {1}",
                            tried == -1 ? 1 : 2, i));
                    }
                }
                //only retries when remote was not passed in, on the first try, and when the first packet was never received
                if (timedOut)
                    return await GetParsedServers(cancelToken, limit, null, cur).ConfigureAwait(false);
                seed = ParseResponse(servers, response, limit);
                if (seed == null)
                    throw new Exception("Bad packet recieved.");
                i++;
            } while ((i < maxIterations) && !seed.Equals("0.0.0.0:0") && !seed.Equals(lastSeed));
            return servers;
        }
开发者ID:SIXNetworks,项目名称:withSIX.Desktop,代码行数:55,代码来源:SourceMasterQuery.cs

示例10: ConsumeOneAsync

 private static async Task ConsumeOneAsync(UdpClient client, IPAddress ipAddress, int port)
 {
     client.Connect(ipAddress, port);
     var bytes = Encoding.UTF8.GetBytes(Constants.ClientToServer);
     var tasks = new[]
     {
         client.SendAsync(bytes, bytes.Length),
         ReceiveAndCheckAsync(client, Constants.ServerToClient)
     };
     await Task.WhenAll(tasks);
 }
开发者ID:axxeny,项目名称:ServerEfficiencyTest,代码行数:11,代码来源:UdpConsumer.cs

示例11: sendUnicastBytesAsync

 public async Task sendUnicastBytesAsync(byte[] bytes, int port)
 {
     try
     {
         if (bytes.Count() <= 0) return;
         UdpClient trasport = new UdpClient();
         trasport.Connect("127.0.0.1", port);
         await trasport.SendAsync(bytes, bytes.Length);
         trasport.Close();
     }
     catch { }
 }
开发者ID:gontcaliuba,项目名称:Distributed_semistructured_data_processing,代码行数:12,代码来源:UDPSenderReceiver.cs

示例12: broadcast

        protected async Task broadcast(String message, int port)
        {
            UdpClient udpClient = new UdpClient();
            udpClient.EnableBroadcast = true;
            udpClient.MulticastLoopback = true;
            udpClient.ExclusiveAddressUse = false;

            IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, port);
            byte[] bytes = Encoding.ASCII.GetBytes(message);
            await udpClient.SendAsync(bytes, bytes.Length, ip);
            udpClient.Close();
        }
开发者ID:864668723,项目名称:128,代码行数:12,代码来源:FileTransferForm.cs

示例13: sendBroadcastBytesAsync

 public async Task sendBroadcastBytesAsync(byte[] bytes, int port)
 {
     try
     {
         if (bytes.Count() <= 0) return;
         UdpClient trasport = new UdpClient();
         trasport.Connect(IPAddress.Broadcast, port);
         await trasport.SendAsync(bytes, bytes.Length);
         trasport.Close();
     }
     catch { }
 }
开发者ID:gontcaliuba,项目名称:Distributed_semistructured_data_processing,代码行数:12,代码来源:UDPSenderReceiver.cs

示例14: 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

示例15: BroadcastGameInstanceAsync

		/// <summary>
		/// Broadcasts the current game information so that other instances can find players.
		/// </summary>
		/// <param name="gameInstance">the game information</param>
		/// <returns><c>true</c>, if message was sent, <c>false</c> otherwise.</returns>
		public async Task<bool> BroadcastGameInstanceAsync(NetworkGameInstance gameInstance, CancellationToken ct = default(CancellationToken))
		{
			int bytesSent = 0;
			var json = gameInstance.ToJsonString ();
			using (var udpClient = new UdpClient ())
			{ 
				udpClient.EnableBroadcast = true;
				var recipient = new IPEndPoint (IPAddress.Broadcast, this.Port);
				var data = Encoding.UTF8.GetBytes (json);
				bytesSent = await udpClient.SendAsync (data, data.Length, recipient);
				udpClient.Close ();
			}

			return bytesSent == json.Length;
		}
开发者ID:Krumelur,项目名称:Pyramid,代码行数:20,代码来源:UDPNetworkService.cs


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