ReceiveAsync() 공개 메소드

public ReceiveAsync ( ) : Task
리턴 Task
        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));
                }
            }
        }
예제 #2
1
        /// <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);
            }
        }
예제 #3
0
        public void TestUDPPacket()
        {
            SharpNet.OnReceiveUDPPacketHandler Handler = async(UDPPacket Packet) =>
            {
                if (Packet.DestPort == remotePort)
                {
                    UDPPacket echo = new UDPPacket(new byte[] { 1, 2, 3, 4, 5 });
                    echo.SourceIP   = Packet.DestIP;
                    echo.DestIP     = Packet.SourceIP;
                    echo.SourcePort = Packet.DestPort;
                    echo.DestPort   = Packet.SourcePort;
                    await net.SendIPPacketAsync(echo);
                }
            };
            net.OnReceiveUDPPacket += Handler;

            CancellationTokenSource cts = new CancellationTokenSource();
            int tx = 0;
            int rx = 0;

            Task.Run(() =>
            {
                while (true)
                {
                    //byte[] data = client.Receive(ref remote);
                    byte[] data = client.ReceiveAsync().Result.Buffer;
                    foreach (var d in data)
                    {
                        Trace.Write(d);
                    }
                    rx++;
                }
            }, cts.Token);

            Task.Run(() =>
            {
                while (true)
                {
                    client.Send(new byte[] { 1, 2, 3, 4 }, 4, remote);
                    tx++;
                    Task.Delay(500).Wait();
                }
            }, cts.Token);
            Task.Delay(5000).Wait();
            cts.Cancel();
            net.OnReceiveUDPPacket -= Handler;
            Assert.IsTrue((rx == tx) && (rx != 0), "Send echo back received number does not match");
        }
예제 #4
0
 private void Run()
 {
     Task.Run(async() =>
     {
         client.Client.Bind(new IPEndPoint(IPAddress.Any, 0));
         _tcs.SetResult(true);
         using (client)
         {
             while (_isRunning)
             {
                 try
                 {
                     var result   = await client.ReceiveAsync();
                     lastActivity = DateTime.UtcNow;
                     var sent     = await _server.SendAsync(result.Buffer, result.Buffer.Length, _clientEndpoint);
                     Console.WriteLine($"{sent} bytes sent from a return message of {result.Buffer.Length} bytes from {_remoteServer} to {_clientEndpoint}");
                 }
                 catch (Exception ex)
                 {
                     Console.WriteLine($"An exception occurred while recieving a server datagram : {ex}");
                 }
             }
         }
     });
 }
예제 #5
0
        private async Task ReceiveText()
        {
            var remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);

            while (true)
            {
                try
                {
                    //var buffer = _receiveClient.Receive(ref remoteEndPoint);
                    var buffer = await _receiveClient.ReceiveAsync();

                    if (buffer.Buffer.Length > 0)
                    {
                        string message = Encoding.ASCII.GetString(buffer.Buffer);
                        Dispatcher.Invoke(() => { TbReceiveContext.Text += message + Environment.NewLine; });
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
                finally
                {
                    Thread.Sleep(1000);
                }
            }
        }
예제 #6
0
        public async Task <Edison.Plugin.Common.Net.UdpReceiveResult> ReceiveAsync()
        {
            var received = await _client.ReceiveAsync();

            return(new Edison.Plugin.Common.Net.UdpReceiveResult(
                       received.Buffer,
                       new IPEndpoint(received.RemoteEndPoint.Address.ToString(), received.RemoteEndPoint.Port)));
        }
예제 #7
0
        public async Task <ReadDataResult> ReadDataAsync(int count, CancellationToken cancellationToken)
        {
            var result = await _client.ReceiveAsync();

            return(new ReadDataResult
            {
                Data = result.Buffer,
                Length = result.Buffer.Length
            });
        }
예제 #8
0
        private async void InitListener()
        {
            while (true)
            {
                var result = await udpServer.ReceiveAsync();

                var message = DateTime.Now.ToString("t") + ": " + Encoding.UTF8.GetString(result.Buffer);

                lbMessages.Invoke(new Action(() => lbMessages.Items.Add(message)));
            }
        }
        private void ReceiveData(IAsyncResult ar)
        {
            try
            {
                System.Net.Sockets.UdpClient listener = (System.Net.Sockets.UdpClient)ar.AsyncState;
                byte[] data = listener.EndReceive(ar, ref endpoint);
#endif
                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)
                {
#if NETSTANDARD1_5
                    result = await listener.ReceiveAsync();

                    ReceiveData(result, client);
#else
                    listener.BeginReceive(new AsyncCallback(ReceiveData), listener);
#endif
                }
            }
        }
예제 #10
0
        public void StartUdpServer (Form2 form2)
        {
            //myTimer.Interval = 50;
            //myTimer.Tick += new EventHandler(myTimerTick);
            publicForm2 = form2;
            JsonHelper jsh = new JsonHelper();
            Task.Run(async () =>
            {

                using (var udpClient = new UdpClient(9992))
                {
                    StartConversation2(udpClient);
                   // SetTime(udpClient);
                    //string path = @"Jsons/" + jsh.deleteAllButNumbers(DateTime.Now.ToString()) + ".txt";
                    //File.Create(path);
                    string udpString = "";
                    while (true)
                    {
                        //IPEndPoint object will allow us to read datagrams sent from any source.
                        var receivedResults = await udpClient.ReceiveAsync();
                        udpString = Encoding.ASCII.GetString(receivedResults.Buffer);

                        //using (StreamWriter writetext = new StreamWriter(path, true))
                        //{
                        //    writetext.WriteLine(udpString);
                        //}

                        // Blink(form2);

                        form2.Controls.Find("label3", true).FirstOrDefault().BackColor = Color.Green;
                        //   TODO: timer, ktery za chvilku zmeni barvu zpet na cervenou

                       
                        //myTimer.Start();

                        Monitor.Enter(lstBuffer);
                            lstBuffer.Add(udpString);
                            Monitor.Exit(lstBuffer);
                         //  MessageBox.Show(loggingEvent);
                        
                        
                                               
                    }
                }
            });
        }
 public async Task<UdpReceiveResult> receiveBytesAsync(int port)
 {
     while (true)
     {
         try
         {
             UdpClient trasport = new UdpClient(port);
             UdpReceiveResult result = await trasport.ReceiveAsync();
             trasport.Close();
             return result;
         }
         catch 
         {
             Thread.Sleep(10);
         }
     }
     
 }
예제 #12
0
        public async Task SendTest()
        {
            // Arrange
            var package = new ArtDmxPackage(new byte[] { 1, 2 });
            var expected = package.GetBytes();
            expected[12] = 2;
            var receiver = new UdpClient(Sender.ArtNetDefaultPort);
            var sender = new Sender("127.0.0.1");

            // Act
            var t = receiver.ReceiveAsync();
            await sender.SendAsync(package);
            var actual = (await t).Buffer;

            // Assert
            Assert.IsNotNull(actual);
            CollectionAssert.AreEqual(expected, actual);
        }
예제 #13
0
        public async Task Start(string remoteServerIp, ushort remoteServerPort, ushort localPort, string localIp = null)
        {
            var clients = new ConcurrentDictionary <IPEndPoint, UdpClient>();

            var server = new System.Net.Sockets.UdpClient(AddressFamily.InterNetworkV6);

            server.Client.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
            IPAddress localIpAddress = string.IsNullOrEmpty(localIp) ? IPAddress.IPv6Any : IPAddress.Parse(localIp);

            server.Client.Bind(new IPEndPoint(localIpAddress, localPort));
            Console.WriteLine($"UDP proxy started :{localIpAddress}|{localPort} -> {remoteServerIp}|{remoteServerPort}");
            var _ = Task.Run(async() =>
            {
                while (true)
                {
                    await Task.Delay(10000);
                    foreach (var client in clients.ToArray())
                    {
                        if (client.Value.lastActivity + TimeSpan.FromSeconds(60) < DateTime.UtcNow)
                        {
                            UdpClient c;
                            clients.TryRemove(client.Key, out c);
                            client.Value.Stop();
                        }
                    }
                }
            });

            while (true)
            {
                try
                {
                    var message = await server.ReceiveAsync();

                    var endpoint = message.RemoteEndPoint;
                    var client   = clients.GetOrAdd(endpoint, ep => new UdpClient(server, endpoint, new IPEndPoint(IPAddress.Parse(remoteServerIp), remoteServerPort)));
                    await client.SendToServer(message.Buffer);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"an exception occurred on recieving a client datagram: {ex}");
                }
            }
        }
예제 #14
0
        private static void Main()
        {
            using (var client = new UdpClient(Sender.ArtNetDefaultPort))
            {
                Console.WriteLine("Waiting for data.");

                while (true)
                {
                    var bytes = client.ReceiveAsync().Result.Buffer;
                    Console.WriteLine();
                    Console.WriteLine(BitConverter.ToString(bytes));
                    var pairs = ByteHelper.GetAddressesAndValuesFromMessage(bytes);
                    foreach (var pair in pairs)
                    {
                        Console.WriteLine("{0:000} = {1:000}", pair.Address, pair.Value);
                    }
                }
            }
        }
예제 #15
0
      public async Task ReceiveMessagesAsync() {
         UdpClient objClient = null;
         try {
            while(true) {
               objClient = new UdpClient(LocalEndPoint);

               IPEndPoint objRemoteEndPoint;
               UdpReceiveResult objResult = await objClient.ReceiveAsync();
               objRemoteEndPoint = objResult.RemoteEndPoint;

               string strText = Encoding.UTF8.GetString(objResult.Buffer);

               await richTextBox1.Dispatcher.InvokeAsync(() => { richTextBox1.AppendText($"{objRemoteEndPoint.Address}:{objRemoteEndPoint.Port} {strText}\n"); });
               objClient.Close();
            }
         }
         catch(Exception ex) {
            MessageBox.Show("ReceiveMessageAsync " + ex.Message);
         }
      }
        public override void Start()
#endif
        {
            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);
#if NETSTANDARD1_5
            var receive = await listener.ReceiveAsync();

            ReceiveData(receive, listener);
#else
            listener.BeginReceive(new AsyncCallback(ReceiveData), listener);
#endif
        }
예제 #17
0
        public static IList<IPEndPoint> FindServers()
        {
            var rt = new List<IPEndPoint>();

            foreach (var ip in GetLocalIPs())
            {
                UdpClient client = new UdpClient();

                IPEndPoint sender = new IPEndPoint(IPAddress.Any, 8005);
                client.Send(Encoding.UTF8.GetBytes(QUERY_MESSAGE), QUERY_MESSAGE.Length, new IPEndPoint(IPAddress.Broadcast, 8002));
                var receiveTask = client.ReceiveAsync();

                receiveTask.Wait(500);
                if (!receiveTask.IsCompleted || Encoding.UTF8.GetString(receiveTask.Result.Buffer) != RESPONSE_MESSAGE)
                    continue;

                rt.Add(receiveTask.Result.RemoteEndPoint);
            }

            return rt;
        }
예제 #18
0
        public static void WhenReceived(this UdpClient client, Action <UdpReceiveResult> action)
        {
            if (action == null)
            {
                throw new ArgumentNullException();
            }
            var key = client.GetHashCode();

            if (udp_received_actions.ContainsKey(key))
            {
                var temp = Delegate.Combine(udp_received_actions[key], action);
                udp_received_actions[key] = temp;
            }
            else
            {
                udp_received_actions[key] = action;
            }

            if (task_tokens.ContainsKey(key))
            {
                return;
            }
            var cts     = new CancellationTokenSource();
            var context = SynchronizationContext.Current;

            Task.Run(async() =>
            {
                while (true)
                {
                    try
                    {
                        if (cts.IsCancellationRequested)
                        {
                            break;
                        }
                        var r = await client.ReceiveAsync();
                        if (udp_received_actions.ContainsKey(key))
                        {
                            var a = udp_received_actions[key];
                            if (context == null)
                            {
                                a.DynamicInvoke(r);
                            }
                            else
                            {
                                context.Post(_ =>
                                {
                                    a.DynamicInvoke(r);
                                }, null);
                            }
                        }
                    }
                    catch
                    {
                        if (task_tokens.TryRemove(key, out cts))
                        {
                            cts.Dispose();
                        }
                        break;
                    }
                }
            }, cts.Token).ConfigureAwait(false);
            task_tokens[key] = cts;
        }
예제 #19
0
 //
 // Summary:
 //     Receives a datagram from a remote host asynchronously.
 //
 // Parameters:
 //   requestCallback:
 //     An System.AsyncCallback delegate that references the method to invoke when the
 //     operation is complete.
 //
 //   state:
 //     A user-defined object that contains information about the receive operation.
 //     This object is passed to the requestCallback delegate when the operation is complete.
 //
 // Returns:
 //     An System.IAsyncResult object that references the asynchronous receive.
 public static IAsyncResult BeginReceive(this UdpClient client, AsyncCallback requestCallback, object state)
 {
     return(TaskToApm.Begin(client.ReceiveAsync(), requestCallback, state));
 }
예제 #20
0
 public Task <UdpReceiveResult> ReceiveAsync()
 {
     return(_udpClient.ReceiveAsync());
 }
예제 #21
-1
 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);
         }
     }
 }
예제 #22
-1
        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;
        }
예제 #23
-1
        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);
            }
        }
예제 #24
-1
 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);
     }
 }
예제 #25
-1
		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);
				}
			}
		}
예제 #26
-1
        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;
        }
예제 #27
-1
 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;
 }
예제 #28
-1
 private void Receive(UdpClient udpClient)
 {
     udpClient.ReceiveAsync().ContinueWith(res =>
     {
         if (DataReceived != null)
             DataReceived(res.Result.RemoteEndPoint, CommandBase.Parse(res.Result.Buffer));
         Receive(udpClient);
     });
 }
예제 #29
-1
 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);
     }
 }
예제 #30
-1
        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();
            }
        }
예제 #31
-1
        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);
            }
        }
예제 #32
-1
        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);
        }
예제 #33
-1
		/// <summary>
		/// Scans the network for game instances sending a broadcast.
		/// </summary>
		/// <returns>The game instances.</returns>
		public async Task<NetworkGameInstance> DiscoverGameInstanceAsync (CancellationToken ct = default(CancellationToken))
		{
			NetworkGameInstance instance = null;
			using(var client = new UdpClient (this.Port))
			{
				UdpReceiveResult receiveResult = await client.ReceiveAsync ();
				string json = Encoding.UTF8.GetString (receiveResult.Buffer);
				instance = json.FromJsonString <NetworkGameInstance>();
				// With UDP, the sender IP can be obtained upon reception of the message.
				instance.SenderAddress = receiveResult.RemoteEndPoint.Address.ToString ();
			}

			return instance;
		}
예제 #34
-1
    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();
      }
    }
        public async Task TestUdpTraceListener()
        {
            int port = 11000;
            var udpclient = new UdpClient(port);

            var traceSource = new TraceSource("UnitTestLogger");
            traceSource.Listeners.Remove("Default");
            traceSource.Switch.Level = SourceLevels.All;
            traceSource.Listeners.Add(new UdpTraceListener(IPAddress.Loopback, port));
            
            traceSource.TraceEvent(TraceEventType.Information, 100, "Boris");

            var dgram = await udpclient.ReceiveAsync();
            var receivedText = Encoding.UTF8.GetString(dgram.Buffer);
            Assert.Equal("UnitTestLogger Information: 100 : ", receivedText);

            dgram = await udpclient.ReceiveAsync();
            receivedText = Encoding.UTF8.GetString(dgram.Buffer);
            Assert.Equal("Boris\r\n", receivedText);

            udpclient.Close();
            traceSource.Close();
        }
예제 #36
-1
        public UdpCanPort(IPEndPoint LocalEnpPoint, IPEndPoint RemoteEndPoint)
        {
            _client = new UdpClient(LocalEnpPoint);
            _client.Connect(RemoteEndPoint);

            IConnectableObservable<ITransaction<CanFrame>> rx =
                Observable.Defer(() => _client.ReceiveAsync().ToObservable())
                          .Repeat()
                          .Select(CreateCanTransaction)
                          .Publish();
            Rx = rx;
            _rxConnection = rx.Connect();

            Options = new UdpCanPortOptions();
        }
예제 #37
-1
 public async Task<ServerInfoResult> GetServerInfo()
 {
     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});
         requestPacket.Add(0x54);
         requestPacket.AddRange(Encoding.ASCII.GetBytes("Source Engine Query"));
         requestPacket.Add(0x00);
         await client.SendAsync(requestPacket.ToArray(), requestPacket.ToArray().Length);
         UdpReceiveResult response = await client.ReceiveAsync();
         return ServerInfoResult.Parse(response.Buffer);
     }
 }
예제 #38
-1
        private async void FindServer(TaskCompletionSource<IPEndPoint> taskCompletionSource, int timeout)
        {
            // Create a udp client
            var client = new UdpClient(new IPEndPoint(IPAddress.Any, GetRandomUnusedPort()));

            client.Client.ReceiveTimeout = timeout;

            // Construct the message the server is expecting
            var bytes = Encoding.UTF8.GetBytes("who is MediaBrowserServer?");

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

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

            try
            {
                // Get a result back
                var result = await client.ReceiveAsync().ConfigureAwait(false);

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

                    // Expected response : MediaBrowserServer|192.168.1.1:1234
                    // If the response is what we're expecting, proceed
                    if (text.StartsWith("mediabrowserserver", StringComparison.OrdinalIgnoreCase))
                    {
                        text = text.Split('|')[1];

                        var vals = text.Split(':');

                        var endpoint = new IPEndPoint(IPAddress.Parse(vals[0]), int.Parse(vals[1]));

                        taskCompletionSource.SetResult(endpoint);
                        return;
                    }
                }

                taskCompletionSource.SetException(new ArgumentException("Unexpected response"));
            }
            catch (SocketException ex)
            {
                taskCompletionSource.SetException(ex);
            }
        }
예제 #39
-1
        public async Task<MonoServerInformation> SearchServer(CancellationToken token)
        {
            using (var udp = new UdpClient(new IPEndPoint(IPAddress.Any, 15000)))
            {
                Task result = await Task.WhenAny(udp.ReceiveAsync(), Task.Delay(500, token));
                var task = result as Task<UdpReceiveResult>;
                if (task != null)
                {
                    UdpReceiveResult udpResult = task.Result;
                    string msg = Encoding.Default.GetString(udpResult.Buffer);
                    return new MonoServerInformation { Message = msg, IpAddress = udpResult.RemoteEndPoint.Address };
                }
            }

            return null;
        }
예제 #40
-1
        public Instance(IParser packetParser, IPEndPoint localPacketEndpoint)
        {
            _packetParser = packetParser;
            _localPacketEndpoint = localPacketEndpoint;

            _udpClient = new UdpClient();
            _udpClient.Client.Bind(_localPacketEndpoint);

            _readings = Observable.FromAsync(() => _udpClient.ReceiveAsync()).Repeat()
                                  .Select(result => result.Buffer)
                                  .Select(Encoding.ASCII.GetString)
                                  .Do(Instrumentation.Packet.Endpoint.Receive)
                                  .SelectMany(_packetParser.GetReadings)
                                  .Do(Instrumentation.Packet.Endpoint.Reading)
                                  .Publish();
        }
예제 #41
-1
        public void CanLoadThousandBots()
        {
            UdpClient udpServer = new UdpClient(44453);
            IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 44453);
            Core c = new Core();
            for (int i = 0; i < 1000; i++)
            {
                Task<UdpReceiveResult> result = udpServer.ReceiveAsync();
                BotClient client = c.AddBot();
                client.Session.Connect(endpoint);
                client.Session.SendAsync(Encoding.ASCII.GetBytes("Testing: " + i));

                Assert.AreEqual<string>("Testing: " + i, Encoding.ASCII.GetString(result.Result.Buffer));
            }
            Assert.AreEqual<int>(1000, c.BotClients.Count);
        }
예제 #42
-1
        public static async Task Test()
        {
            using (var udp = new UdpClient())
            {
                var listenEndpoint = new IPEndPoint(IPAddress.Any, 5321);

                udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                udp.ExclusiveAddressUse = false;
                udp.Client.Bind(listenEndpoint);
                while (true)
                {
                    var response = await udp.ReceiveAsync();
                    Console.WriteLine(response.RemoteEndPoint.Address.ToString());
                }
            }
        }