private static void Receive(IAsyncResult result) { if (connection == null || result == null) { return; } IPEndPoint source = null; byte[] message = connection.EndReceive(result, ref source); connection.BeginReceive(new AsyncCallback(Receive), connection); if (source.Address.Equals(localhost)) { if (!portMap.ContainsKey(source)) { connection?.SendAsync(new byte[] { 244, Convert.ToByte((portMap[source] = MIDI.ConnectAbleton()).Name.Substring(18)) }, 2, source); } if (message[0] < 128) { NoteOnMessage msg = new NoteOnMessage(Channel.Channel1, (Key)message[0], message[1]); portMap[source].NoteOn(null, in msg); } else if (message[0] == 245) { MIDI.Disconnect(portMap[source]); portMap.Remove(source); } } }
protected void AsynCsendMessage(string message) { if (String.IsNullOrWhiteSpace(message)) { throw (new Exception(BasicErrorMessage.InvalidSendString)); } byte[] data = Encoding.UTF8.GetBytes(message); client?.SendAsync(data, data.Length, remoteEndPoint); }
/// <summary> /// 向特定ip的主机的端口发送数据报 /// </summary> /// <param name="msg"></param> public void Send(OutMsg outMsg) { if (outMsg == null) { return; } byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(outMsg)); client?.SendAsync(data, data.Length, serverPoint); }
private async void FlightConnect_FlightStatusUpdated(object sender, FlightStatusUpdatedEventArgs e) { viewModel.FlightStatus = e.FlightStatus; if (isReady) { try { var gpsData = Encoding.UTF8.GetBytes($"XGPSFS2020,{e.FlightStatus.Longitude},{e.FlightStatus.Latitude},{e.FlightStatus.Altitude},{e.FlightStatus.TrueHeading},{e.FlightStatus.GroundSpeed * KnotsToMetersPerSecond}"); var statusData = Encoding.UTF8.GetBytes($"XATTFS2020,{e.FlightStatus.TrueHeading},{-e.FlightStatus.Pitch},{-e.FlightStatus.Bank}"); await client?.SendAsync(gpsData, gpsData.Length); await client?.SendAsync(statusData, statusData.Length); } catch (Exception ex) { logger.LogError(ex, "Cannot send flight status!"); } } }
private async void SendBack(string message) { byte[] dataToSend = System.Text.Encoding.ASCII.GetBytes(message); await server.SendAsync(dataToSend, dataToSend.Length, client); }
private async Task BroadcastProbeAsync() { Debug.WriteLine($"P: Broadcasting probe with discovery port {Beacon.DiscoveryPort}"); var probe = Beacon.Encode(BeaconType).ToArray(); await udp.SendAsync(probe, probe.Length, new IPEndPoint(IPAddress.Broadcast, Beacon.DiscoveryPort)); }
public Task <int> WriteAsync(byte[] source, CancellationToken cancellationToken = default) => _client?.SendAsync(source, source.Length).WithCancellation(cancellationToken) ?? throw new ObjectDisposedException(nameof(UdpConnection));
public void SendToRecvFromAsync_Datagram_UDP_UdpClient(IPAddress leftAddress, IPAddress rightAddress) { // TODO #5185: harden against packet loss const int DatagramSize = 256; const int DatagramsToSend = 256; const int AckTimeout = 1000; const int TestTimeout = 30000; using (var left = new UdpClient(new IPEndPoint(leftAddress, 0))) using (var right = new UdpClient(new IPEndPoint(rightAddress, 0))) { var leftEndpoint = (IPEndPoint)left.Client.LocalEndPoint; var rightEndpoint = (IPEndPoint)right.Client.LocalEndPoint; var receiverAck = new ManualResetEventSlim(); var senderAck = new ManualResetEventSlim(); var receivedChecksums = new uint?[DatagramsToSend]; int receivedDatagrams = 0; Task receiverTask = Task.Run(async () => { for (; receivedDatagrams < DatagramsToSend; receivedDatagrams++) { UdpReceiveResult result = await left.ReceiveAsync(); receiverAck.Set(); Assert.True(senderAck.Wait(AckTimeout)); senderAck.Reset(); Assert.Equal(DatagramSize, result.Buffer.Length); Assert.Equal(rightEndpoint, result.RemoteEndPoint); int datagramId = (int)result.Buffer[0]; Assert.Null(receivedChecksums[datagramId]); receivedChecksums[datagramId] = Fletcher32.Checksum(result.Buffer, 0, result.Buffer.Length); } }); var sentChecksums = new uint[DatagramsToSend]; int sentDatagrams = 0; Task senderTask = Task.Run(async () => { var random = new Random(); var sendBuffer = new byte[DatagramSize]; for (; sentDatagrams < DatagramsToSend; sentDatagrams++) { random.NextBytes(sendBuffer); sendBuffer[0] = (byte)sentDatagrams; int sent = await right.SendAsync(sendBuffer, DatagramSize, leftEndpoint); Assert.True(receiverAck.Wait(AckTimeout)); receiverAck.Reset(); senderAck.Set(); Assert.Equal(DatagramSize, sent); sentChecksums[sentDatagrams] = Fletcher32.Checksum(sendBuffer, 0, sent); } }); Assert.True(Task.WaitAll(new[] { receiverTask, senderTask }, TestTimeout)); for (int i = 0; i < DatagramsToSend; i++) { Assert.NotNull(receivedChecksums[i]); Assert.Equal(sentChecksums[i], (uint)receivedChecksums[i]); } } }
///<summary>これを定期的に呼んで再接続やFriendの取得をやらせる</summary> public async ValueTask <int> ConnectStreamers() { if (!await db.ExistThisPid().ConfigureAwait(false)) { Environment.Exit(1); } int ActiveStreamers = 0; //再接続が不要だったやつの数 ActionBlock <UserStreamer> ConnectBlock = new ActionBlock <UserStreamer>( async(Streamer) => { try { UserStreamer.NeedConnectResult NeedConnect = Streamer.NeedConnect(); //初回とRevoke疑いのときだけVerifyCredentials()する //プロフィールを取得したい if (NeedConnect == UserStreamer.NeedConnectResult.Postponed) { return; } else if (NeedConnect == UserStreamer.NeedConnectResult.First) { switch (await Streamer.VerifyCredentials().ConfigureAwait(false)) { case UserStreamer.TokenStatus.Locked: Streamer.PostponeConnect(); return; case UserStreamer.TokenStatus.Revoked: await RevokeRetry(Streamer).ConfigureAwait(false); return; case UserStreamer.TokenStatus.Failure: return; case UserStreamer.TokenStatus.Success: RevokeRetryUserID.TryRemove(Streamer.Token.UserId, out byte gomi); NeedConnect = UserStreamer.NeedConnectResult.JustNeeded; //無理矢理接続処理に突っ込む #ウンコード break; } } //Streamに接続したりRESTだけにしたり if (NeedConnect == UserStreamer.NeedConnectResult.StreamConnected) { if (Streamer.NeedStreamSpeed() == UserStreamer.NeedStreamResult.RestOnly) { Streamer.DisconnectStream(); return; } else { Interlocked.Increment(ref ActiveStreamers); } } else { //TLの速度を測定して必要ならStreamに接続 switch (await Streamer.RecieveRestTimelineAuto().ConfigureAwait(false)) { case UserStreamer.TokenStatus.Locked: Streamer.PostponeConnect(); break; case UserStreamer.TokenStatus.Revoked: await RevokeRetry(Streamer).ConfigureAwait(false); break; default: UserStreamer.NeedStreamResult NeedStream = Streamer.NeedStreamSpeed(); if (NeedStream == UserStreamer.NeedStreamResult.Stream) { Streamer.RecieveStream(); Interlocked.Increment(ref ActiveStreamers); } //DBが求めていればToken読み込み直後だけ自分のツイートも取得(初回サインイン狙い if (Streamer.NeedRestMyTweet) { Streamer.NeedRestMyTweet = false; await Streamer.RestMyTweet().ConfigureAwait(false); //User streamに繋がない場合はこっちでフォローを取得する必要がある if (NeedStream != UserStreamer.NeedStreamResult.Stream) { await Streamer.RestFriend().ConfigureAwait(false); } await Streamer.RestBlock().ConfigureAwait(false); await db.StoreRestDonetoken(Streamer.Token.UserId).ConfigureAwait(false); } break; } } } catch (Exception e) { Console.WriteLine("ConnectBlock Faulted: {0}", e); } finally { Streamer.ConnectWaiting = false; } }, new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = config.crawl.ReconnectThreads, BoundedCapacity = config.crawl.ReconnectThreads << 1, //これでもawaitする SingleProducerConstrained = true, }); SetMaxConnections(0); Stopwatch sw = new Stopwatch(); sw.Start(); await ShowCount(); foreach (KeyValuePair <long, UserStreamer> s in Streamers.ToArray()) //ここでスナップショットを作る { if (!s.Value.ConnectWaiting) { s.Value.ConnectWaiting = true; await ConnectBlock.SendAsync(s.Value).ConfigureAwait(false); } do { SetMaxConnections(ActiveStreamers); if (sw.ElapsedMilliseconds > 60000) { //ここでGCする #ウンコード sw.Restart(); await ShowCount(); //GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; //これは毎回必要らしい //GC.Collect(); } //ツイートが詰まってたら休む if (UserStreamerStatic.NeedConnectPostpone()) { await Task.Delay(1000).ConfigureAwait(false); } } while (UserStreamerStatic.NeedConnectPostpone()); } ConnectBlock.Complete(); await ConnectBlock.Completion.ConfigureAwait(false); return(ActiveStreamers); //カウンターを表示したりいろいろ async Task ShowCount() { Counter.PrintReset(); await WatchDogUdp.SendAsync(BitConverter.GetBytes(ThisPid), sizeof(int), WatchDogEndPoint); } }
/// <summary> /// Discovers agents of the specified version in a specific time interval. /// </summary> /// <param name="version">The version.</param> /// <param name="broadcastAddress">The broadcast address.</param> /// <param name="community">The community.</param> /// <param name="interval">The discovering time interval, in milliseconds.</param> /// <remarks><paramref name="broadcastAddress"/> must be an IPv4 address. IPv6 is not yet supported here.</remarks> public void Discover(VersionCode version, IPEndPoint broadcastAddress, OctetString community, int interval) { if (broadcastAddress == null) { throw new ArgumentNullException(nameof(broadcastAddress)); } if (version != VersionCode.V3 && community == null) { throw new ArgumentNullException(nameof(community)); } var addressFamily = broadcastAddress.AddressFamily; if (addressFamily == AddressFamily.InterNetworkV6) { throw new ArgumentException("IP v6 is not yet supported.", nameof(broadcastAddress)); } byte[] bytes; _requestId = Messenger.NextRequestId; if (version == VersionCode.V3) { // throw new NotSupportedException("SNMP v3 is not supported"); var discovery = new Discovery(Messenger.NextMessageId, _requestId, Messenger.MaxMessageSize); bytes = discovery.ToBytes(); } else { var message = new GetRequestMessage(_requestId, version, community, _defaultVariables); bytes = message.ToBytes(); } using (var udp = new UdpClient(addressFamily)) { #if (!CF) udp.EnableBroadcast = true; #endif #if NET471 udp.Send(bytes, bytes.Length, broadcastAddress); #else AsyncHelper.RunSync(() => udp.SendAsync(bytes, bytes.Length, broadcastAddress)); #endif var activeBefore = Interlocked.CompareExchange(ref _active, Active, Inactive); if (activeBefore == Active) { // If already started, we've nothing to do. return; } _bufferSize = udp.Client.ReceiveBufferSize = Messenger.MaxMessageSize; #if ASYNC Task.Factory.StartNew(() => AsyncBeginReceive(udp.Client)); #else Task.Factory.StartNew(() => AsyncReceive(udp.Client)); #endif Thread.Sleep(interval); Interlocked.CompareExchange(ref _active, Inactive, Active); #if NET471 udp.Close(); #endif } }
public void WriteAsync(byte[] data) { udpClient.SendAsync(data, data.Length); }
public static async Task Run(CancellationToken cancellationToken) { // generate a key pair byte[] privateKey = KeyGeneration.GeneratePrivateKey(); byte[] publicKey = KeyGeneration.GetPublicKeyFromPrivateKey(privateKey); // configuring as a server with the default application key. // messages will be padded to 64 bytes and cannot exceed // 256 bytes. var config = new MicroRatchetConfiguration { ApplicationKey = new byte[32], IsClient = false, MaximumMessageSize = 256, MinimumMessageSize = 64 }; // create the MicroRatchet context var services = new BouncyCastleServices(privateKey); using var context = new MicroRatchetContext(services, config, null); Console.WriteLine($"Starting Server with public key: {publicKey.ToHexString()}"); // Create UDP client. For the server we set // the local endpoint to be localhost, // listening on the configured port. var serverEndpoint = new IPEndPoint(IPAddress.Loopback, PORT); IPEndPoint clientEndpoint = null; using var udp = new UdpClient(serverEndpoint); if (!cancellationToken.IsCancellationRequested) { // in order to get the console, udp stuff, and MR stuff to work // together (even though nothing was written for async), we need // some synchronization. // A background thread reads from the console and pushes messages // into a queue which then in turn get sent to the server by the // Send task. // A receive task handles messages from the server // The receive task handles incoming UDP messages. var messages = new ConcurrentQueue <string>(); var semaphore = new SemaphoreSlim(0); async Task ReceiveTask() { while (!cancellationToken.IsCancellationRequested) { var received = await udp.ReceiveAsync(cancellationToken); Console.WriteLine($"RECEIVED {received.Buffer.Length} bytes"); try { // pass the received data to the MR context var message = context.Receive(received.Buffer); // if ToSendBack is not null, the context has accepted // an incoming initialization message and now is bound // to the session from that client key. if (message.ToSendBack != null) { // send the response back await udp.SendAsync(message.ToSendBack, message.ToSendBack.Length, received.RemoteEndPoint); Console.WriteLine($"SENT {message.ToSendBack.Length} bytes RESPONSE"); if (context.IsInitialized) { // message.ToSendBack != null && context.IsInitialized // typically happens once per session. clientEndpoint = received.RemoteEndPoint; Console.WriteLine($"Server initialized with remote public key {context.GetRemotePublicKey().ToHexString()}."); Console.WriteLine("Type stuff in and press enter to send to the client.\n\n"); } } else if (message.Payload != null) { // if a payload is given, the message contains // data sent by the client, which we print to the console. // The message is always padded to the minimum message size, // so read the incoming message as a null-terminated // string. string msg = message.Payload.DecodeNullTerminatedString(); // Print the decrypted and decoded message to the console Console.WriteLine($"RECEIVED MESSAGE: {msg}"); } } catch (Exception ex) { // one exception you would see in this situation is if second client // tries to initialize a session. Because the context is bound to a remote // public key as soon as a message comes in, and this demo application // contains no logic to handle that situation, it will simply stay bound // to the first session and throw an exception if another client tries to // connect. Console.WriteLine($"An exception was encountered when receiving a message: {ex}"); } } } // the send task dequeues messages, encrypts, and sends // them to the server endpoint as UDP messages. async Task SendTask() { while (!cancellationToken.IsCancellationRequested) { // wait for a message await semaphore.WaitAsync(); messages.TryDequeue(out var payload); // encrypt the message using the context. The message // will be padded to the minimum configured message size. var payloadBytes = Encoding.UTF8.GetBytes(payload); var message = context.Send(payloadBytes); // send as UDP message to the server endpoint. await udp.SendAsync(message, clientEndpoint, cancellationToken); Console.WriteLine($"SENT {payloadBytes.Length} bytes PAYLOAD, resulting in {message.Length} bytes ENCRYPTED MESSAGE"); } } // The console thread reades lines one at a time and // enqueues them for sending. var consoleReadThread = new Thread(_ => { for (; ;) { string line = Console.ReadLine(); if (clientEndpoint != null) { messages.Enqueue(line); semaphore.Release(); } else { Console.WriteLine("Cannot send message as no client has initialized a session"); } } }); // background threads are terminated when the program exits consoleReadThread.IsBackground = true; consoleReadThread.Start(); await Task.WhenAll(ReceiveTask(), SendTask()); } }
async Task NetworkRequestAsync(byte[] requestBytes, TimeSpan scanTime, int retries, int retryDelayMilliseconds, Action <IPAddress, byte[]> onResponse, System.Net.NetworkInformation.NetworkInterface adapter, CancellationToken cancellationToken) { // http://stackoverflow.com/questions/2192548/specifying-what-network-interface-an-udp-multicast-should-go-to-in-net // Xamarin doesn't support this //if (!adapter.GetIPProperties().MulticastAddresses.Any()) // return; // most of VPN adapters will be skipped if (!adapter.SupportsMulticast) { return; // multicast is meaningless for this type of connection } if (OperationalStatus.Up != adapter.OperationalStatus) { return; // this adapter is off or not connected } if (adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback) { return; // strip out loopback addresses } var p = adapter.GetIPProperties().GetIPv4Properties(); if (null == p) { return; // IPv4 is not configured on this adapter } var ipv4Address = adapter.GetIPProperties().UnicastAddresses .FirstOrDefault(ua => ua.Address.AddressFamily == AddressFamily.InterNetwork)?.Address; if (ipv4Address == null) { return; // could not find an IPv4 address for this adapter } var ifaceIndex = p.Index; Debug.WriteLine($"Scanning on iface {adapter.Name}, idx {ifaceIndex}, IP: {ipv4Address}"); using (var client = new UdpClient()) { for (var i = 0; i < retries; i++) { try { var socket = client.Client; if (socket.IsBound) { continue; } socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(ifaceIndex)); client.ExclusiveAddressUse = false; socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, (int)scanTime.TotalMilliseconds); client.ExclusiveAddressUse = false; var localEp = new IPEndPoint(IPAddress.Any, 5353); Debug.WriteLine($"Attempting to bind to {localEp} on adapter {adapter.Name}"); socket.Bind(localEp); Debug.WriteLine($"Bound to {localEp}"); var multicastAddress = IPAddress.Parse("224.0.0.251"); var multOpt = new MulticastOption(multicastAddress, ifaceIndex); socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multOpt); Debug.WriteLine("Bound to multicast address"); // Start a receive loop var shouldCancel = false; var recTask = Task.Run(async () => { try { while (!Volatile.Read(ref shouldCancel)) { var res = await client.ReceiveAsync() .ConfigureAwait(false); onResponse(res.RemoteEndPoint.Address, res.Buffer); } } catch when(Volatile.Read(ref shouldCancel)) { // If we're canceling, eat any exceptions that come from here } }, cancellationToken); var broadcastEp = new IPEndPoint(IPAddress.Parse("224.0.0.251"), 5353); Debug.WriteLine($"About to send on iface {adapter.Name}"); await client.SendAsync(requestBytes, requestBytes.Length, broadcastEp) .ConfigureAwait(false); Debug.WriteLine($"Sent mDNS query on iface {adapter.Name}"); // wait for responses await Task.Delay(scanTime, cancellationToken) .ConfigureAwait(false); Volatile.Write(ref shouldCancel, true); ((IDisposable)client).Dispose(); Debug.WriteLine("Done Scanning"); await recTask.ConfigureAwait(false); return; } catch (Exception e) { Debug.WriteLine($"Execption with network request, IP {ipv4Address}\n: {e}"); if (i + 1 >= retries) // last one, pass underlying out { // Ensure all inner info is captured ExceptionDispatchInfo.Capture(e).Throw(); throw; } } await Task.Delay(retryDelayMilliseconds, cancellationToken).ConfigureAwait(false); } } }
public static void Start() { var config = Settings.Instance[SettingsName]; if (config == null) { Settings.Instance[SettingsName] = connectionInfos.ToJSON(); config = Settings.Instance[SettingsName]; } connectionInfos = config.FromJSON <List <ConnectionInfo> >(); foreach (var connectionInfo in connectionInfos) { if (connectionInfo.Enabled == false) { continue; } log.Info(connectionInfo.ToJSON()); if (connectionInfo.Format == ConnectionFormat.MAVLink) { if (connectionInfo.Protocol == ProtocolType.Udp && connectionInfo.Direction == Direction.Inbound) { try { var client = new UdpClient(connectionInfo.Port); client.BeginReceive(clientdataMAVLink, client); } catch (Exception ex) { log.Error(ex); } continue; } if (connectionInfo.Protocol == ProtocolType.Udp && connectionInfo.Direction == Direction.Outbound) { try { // create and set default dest var client = new UdpClient(connectionInfo.ConfigString, connectionInfo.Port); client.SendAsync(new byte[] { 0 }, 1); client.BeginReceive(clientdataMAVLink, client); } catch (Exception ex) { log.Error(ex); } continue; } if (connectionInfo.Protocol == ProtocolType.Tcp && connectionInfo.Direction == Direction.Outbound) { try { // try anything already connected Task.Run(() => { try { var serial = new TcpSerial(); serial.Host = connectionInfo.ConfigString; serial.Port = connectionInfo.Port.ToString(); serial.ReadBufferSize = 1024 * 300; serial.Open(); // sample 1.2seconds Thread.Sleep(1200); var btr = serial.BytesToRead; var buffer = new byte[btr]; serial.Read(buffer, 0, buffer.Length); //serial.Close(); var parse = new MAVLink.MavlinkParse(); var st = buffer.ToMemoryStream(); while (st.Position < st.Length) { var packet = parse.ReadPacket(st); if (packet != null) { if (packet.msgid == (int)MAVLink.MAVLINK_MSG_ID.HEARTBEAT) { NewMavlinkConnection?.BeginInvoke(null, serial, null, null); return; } } } } catch { } }); } catch (Exception ex) { log.Error(ex); } continue; } if (connectionInfo.Protocol == ProtocolType.Tcp && connectionInfo.Direction == Direction.Inbound) { try { // try anything already connected Task.Run(() => { try { TcpListener listener = new TcpListener(IPAddress.Any, connectionInfo.Port); listener.Start(); var client = listener.AcceptTcpClient(); var serial = new TcpSerial(); serial.client = client; serial.ReadBufferSize = 1024 * 300; serial.Open(); // sample 1.2seconds Thread.Sleep(1200); var btr = serial.BytesToRead; var buffer = new byte[btr]; serial.Read(buffer, 0, buffer.Length); //serial.Close(); var parse = new MAVLink.MavlinkParse(); var st = buffer.ToMemoryStream(); while (st.Position < st.Length) { var packet = parse.ReadPacket(st); if (packet != null) { if (packet.msgid == (int)MAVLink.MAVLINK_MSG_ID.HEARTBEAT) { NewMavlinkConnection?.BeginInvoke(null, serial, null, null); return; } } } } catch { } }); } catch (Exception ex) { log.Error(ex); } continue; } if (connectionInfo.Protocol == ProtocolType.Serial && connectionInfo.Direction == Direction.Outbound) { try { // try anything already connected Task.Run(() => { Parallel.ForEach(SerialPort.GetPortNames(), port => { try { var serial = new SerialPort(port, connectionInfo.Port); serial.ReadBufferSize = 1024 * 300; serial.Open(); // sample 1.2seconds Thread.Sleep(1200); var btr = serial.BytesToRead; var buffer = new byte[btr]; serial.Read(buffer, 0, buffer.Length); serial.Close(); var parse = new MAVLink.MavlinkParse(); var st = buffer.ToMemoryStream(); while (st.Position < st.Length) { var packet = parse.ReadPacket(st); if (packet != null) { if (packet.msgid == (int)MAVLink.MAVLINK_MSG_ID.HEARTBEAT) { NewMavlinkConnection?.BeginInvoke(null, serial, null, null); return; } } } } catch { } }); }); } catch (Exception ex) { log.Error(ex); } continue; } } else if (connectionInfo.Format == ConnectionFormat.Video) { if (connectionInfo.Protocol == ProtocolType.Udp && connectionInfo.Direction == Direction.Inbound) { try { var client = new UdpClient(connectionInfo.Port, AddressFamily.InterNetwork); client.BeginReceive(clientdataVideo, client); } catch (Exception ex) { log.Error(ex); } continue; } if (connectionInfo.Protocol == ProtocolType.Tcp && connectionInfo.Direction == Direction.Inbound) { try { var client = new TcpListener(IPAddress.Any, connectionInfo.Port); client.Start(); client.BeginAcceptTcpClient(clientdatatcpvideo, client); } catch (Exception ex) { log.Error(ex); } continue; } if (connectionInfo.Direction == Direction.Outbound) { NewVideoStream?.BeginInvoke(null, connectionInfos.First(a => a == connectionInfo).ConfigString, null, null); continue; } } } }
public async Task <RadiusPacket> SendAndReceivePacket(RadiusPacket packet, int retries = DEFAULT_RETRIES) { using (UdpClient udpClient = new UdpClient()) { udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, _SocketTimeout); IPAddress hostIP = null; try { // Starting with Vista, we are able to bind to a local endpoint to guarantee the packet // will be sent out a particular interface // This is explained in the following blog // http://blogs.technet.com/b/networking/archive/2009/04/25/source-ip-address-selection-on-a-multi-homed-windows-computer.aspx if (_LocalEndPoint != null) { udpClient.Client.Bind(_LocalEndPoint); } if (!IPAddress.TryParse(_HostName, out hostIP)) { //Try performing a DNS lookup var host = Dns.GetHostEntry(_HostName); hostIP = host.AddressList.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork); if (hostIP == null) { throw new Exception("Resolving " + _HostName + " returned no hits in DNS"); } } } catch (SocketException e) { int hr = Marshal.GetHRForException(e); string hexValue = hr.ToString("X"); //The requested name is valid, but no data of the requested type was found if (hexValue == "80004005") { return(null); } } var endPoint = new IPEndPoint(hostIP, (int)_AuthPort); int numberOfAttempts = 0; do { await udpClient.SendAsync(packet.RawData, packet.RawData.Length, endPoint); try { // Using the synchronous method for the timeout features var result = udpClient.Receive(ref endPoint); RadiusPacket receivedPacket = new RadiusPacket(result); if (receivedPacket.Valid && VerifyAuthenticator(packet, receivedPacket)) { return(receivedPacket); } } catch (SocketException) { //Server isn't responding } numberOfAttempts++; } while (numberOfAttempts < retries); } return(null); }
/// <summary> /// Sends the specified payload. /// </summary> /// <param name="payload">The payload.</param> public Task Send(byte[] payload) { return(_client.SendAsync(payload, payload.Length, _target)); }
public Task SendAsync(byte[] bytes, int bytesLength) => _client.SendAsync(bytes, bytesLength);
public async Task <RadiusPacket> SendAndReceivePacket(RadiusPacket packet, int retries = DEFAULT_RETRIES) { using (UdpClient udpClient = new UdpClient()) { udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, _SocketTimeout); try { IPAddress hostIP; if (IPAddress.TryParse(_HostName, out hostIP)) { udpClient.Connect(hostIP, (int)_AuthPort); } else { udpClient.Connect(_HostName, (int)_AuthPort); } } catch (SocketException e) { int hr = Marshal.GetHRForException(e); string hexValue = hr.ToString("X"); //The requested name is valid, but no data of the requested type was found if (hexValue == "80004005") { return(null); } } var endPoint = (IPEndPoint)udpClient.Client.RemoteEndPoint; int numberOfAttempts = 0; do { await udpClient.SendAsync(packet.RawData, packet.RawData.Length); try { // Using the synchronous method for the timeout features var result = udpClient.Receive(ref endPoint); RadiusPacket receivedPacket = new RadiusPacket(result); if (receivedPacket.Valid && VerifyAuthenticator(packet, receivedPacket)) { return(receivedPacket); } } catch (SocketException) { //Server isn't responding } numberOfAttempts++; } while (numberOfAttempts < retries); } return(null); }
public async Task SendAsync(string line) { var payload = Encoding.UTF8.GetBytes(line); await _udpClient.SendAsync(payload, payload.Length); }
/// <summary> /// Queries the STUN server with the specified IP address for the public IP /// address of the requesting host. /// </summary> /// <param name="address">The IP address of the STUN server to query.</param> /// <param name="port">The port on which the STUN service is running at /// the specified host.</param> /// <param name="timeout">The maximum number of milliseconds to wait for /// a server response before returning to the caller.</param> /// <returns>The public IP address of the requesting host.</returns> /// <exception cref="ArgumentNullException">The address parameter is /// null.</exception> /// <exception cref="ArgumentOutOfRangeException">The port is not between /// 0 and 65535.</exception> /// <exception cref="ProtocolViolationException">The specified STUN /// server returned an erroneous response.</exception> /// <exception cref="SocketException">The specified hostname could not be /// resolved, or an error occurred while sending the request or while /// retrieving the response, or the specified STUN server could not be /// reached.</exception> /// <exception cref="TimeoutException">The specified timeout has /// expired.</exception> public static async Task <IPAddress> Query(IPAddress address, int port = 3478, int timeout = Int32.MaxValue) { address.ThrowIfNull("address"); port.ThrowIfOutOfRange("port", 0, 65535); IPEndPoint IpEp = new IPEndPoint(address, port); var request = new BindingRequest().Serialize(); int rto = initialRto; using (UdpClient udp = new UdpClient()) { // The timeout mechanism is similar to TCP. For details, // refer to RFC 5389, Section 7.2.1. Sending over UDP. for (int tries = 0; tries < rc; tries++) { // Transmit the datagram. await udp.SendAsync(request, request.Length, IpEp); // Set the timeout value on the socket. udp.Client.ReceiveTimeout = rto; try { var res = await udp.ReceiveAsync(); return(BindingResponse.Deserialize(res.Buffer).Address); } catch (SocketException e) { if ((int)e.SocketErrorCode != connectionTimeout) { throw; } timeout = timeout - rto; if (timeout <= 0) { throw new TimeoutException("The timeout has expired."); } } catch (SerializationException) { throw new ProtocolViolationException("The STUN " + "Binding Response is invalid."); } // Increase the timeout value. if (tries < (rc - 1)) { rto = rto * 2; } else { rto = initialRto * rm; } if (timeout < rto) { rto = timeout; } } // Give up. throw new SocketException(connectionTimeout); } }
public static async Task SendAsync(UdpClient client, IEnumerable <byte> datagramEnumerable) { var datagram = datagramEnumerable as byte[] ?? datagramEnumerable.ToArray(); await client.SendAsync(datagram, datagram.Length); }
/// <summary> /// Sends the specified data to the 'default' target of the underlying DatagramSocket. /// There may be no 'default' target. depending on the state of the object. /// </summary> /// <param name="data">A byte array of data to be sent.</param> protected async Task SendAsync(byte[] data) { await _backingUdpClient.SendAsync(data, data.Length); }
private async Task SendQuery(UdpClient client) { await client.SendAsync(InfoRequest, InfoRequest.Length, m_EndPoint); await client.ReceiveAsync(); }
private async Task SendCommands(params byte[] commands) => await _udpClient?.SendAsync(commands, commands.Length);
/// <summary> /// Fetches the status from a Minecraft Bedrock server. /// </summary> /// <param name="timeout">timeout in milliseconds</param> /// <returns></returns> public async Task <BedrockServerStatus> GetStatusAsync(int timeout = 10000) { { byte[] data = new byte[25]; using MemoryStream stream = new MemoryStream(data); using BinaryWriter writer = new BinaryWriter(stream); writer.Write((byte)0x01); // PacketHeader. 0x01 is ID_CONNECTED_PING_OPEN_CONNECTIONS writer.Write(0L); // Current timestamp. Used to calculate ping normally but we don't really care. writer.Write(MagicBytes); // Magic that makes the server reply await client.SendAsync(data, data.Length, new IPEndPoint(address, port)); } Task <UdpReceiveResult> currentResultTask; // If an uncompleted listening task still exists, use it instead of making a new one if (storedResultTask == null || storedResultTask.IsCompleted) { currentResultTask = client.ReceiveAsync(); } else { currentResultTask = storedResultTask; } await Task.WhenAny(currentResultTask, Task.Delay(timeout)); // If currentResultTask is not completed, the timeout occurred if (currentResultTask.IsCompleted == false) { // Store the listening task, as it isn't closeable we must reuse it for the next attempt storedResultTask = currentResultTask; throw new TimeoutException($"Server did not respond within {timeout} ms."); } UdpReceiveResult result = currentResultTask.Result; string information; { using MemoryStream stream = new MemoryStream(result.Buffer); using BinaryReader reader = new BinaryReader(stream); reader.ReadByte(); // header reader.ReadInt64(); // ping id reader.ReadInt64(); // server id reader.ReadBytes(MagicBytes.Length); // magic int stringLength = reader.ReadInt16(); byte[] stringBytes = reader.ReadBytes(stringLength); information = Encoding.UTF8.GetString(stringBytes); } string[] splits = information.Split(";"); if (splits.Length <= 5) { throw new Exception("Invalid data returned from server"); } string minecraftEdition = splits[0]; string name = splits[1]; int protocolVersion = int.Parse(splits[2]); string version = splits[3]; int players = int.Parse(splits[4]); int maxPlayers = int.Parse(splits[5]); string?worldName = splits.Length > 7 ? splits[7] : null; string?gameType = splits.Length > 8 ? splits[8] : null; return(new BedrockServerStatus(minecraftEdition, name, worldName, version, players, maxPlayers, protocolVersion, gameType)); }
static void Receive(IAsyncResult result) { lock (locker) { if (connection == null || result == null) { return; } IPEndPoint source = null; byte[] message = connection?.EndReceive(result, ref source); connection?.BeginReceive(new AsyncCallback(Receive), connection); if (!source.Address.Equals(localhost)) { return; } if (!portMap.ContainsKey(source)) { if (message[0] == 247) { App.Args = new string[] { Encoding.UTF8.GetString(message.Skip(1).ToArray()) }; if (handlingFileOpen) { return; } handlingFileOpen = true; Dispatcher.UIThread.InvokeAsync(async() => { if (Program.Project == null) { App.Windows.OfType <SplashWindow>().First().ReadFile(App.Args[0]); } else { await Program.Project.AskClose(); } App.Args = null; handlingFileOpen = false; }); } else if (message[0] >= 242 && message[0] <= 244) { connection?.SendAsync(new byte[] { 244, Convert.ToByte((portMap[source] = MIDI.ConnectAbleton(244 - message[0])).Name.Substring(18)) }, 2, source); } } else if (message[0] < 128) { portMap[source].HandleNote(message[0], message[1]); } else if (message[0] == 245) { MIDI.Disconnect(portMap[source]); portMap.Remove(source); } else if (message[0] == 246 && Program.Project != null) { Program.Project.BPM = BitConverter.ToUInt16(message, 1); } } }
private async void HandleUdpListenerAsync() { try { UdpReceiveResult receiveResult; try { receiveResult = await _udpListener.ReceiveAsync(); } catch (ObjectDisposedException) { return; } finally { lock (_listenerLock) { _hasActiveUdpListener = false; } } ClientConnectedEventArgs clientConnectedEventArgs = new ClientConnectedEventArgs(ProtocolType.Udp, receiveResult.RemoteEndPoint); await ClientConnected.RaiseAsync(this, clientConnectedEventArgs); if (clientConnectedEventArgs.RefuseConnect) { return; } StartUdpListenerTask(); byte[] buffer = receiveResult.Buffer; DnsMessageBase query; try { query = DnsMessageBase.CreateByFlag(buffer); } catch (Exception e) { throw new Exception("Error parsing dns query", e); } DnsMessageBase response; try { response = await ProcessMessageAsync(query, ProtocolType.Udp, receiveResult.RemoteEndPoint); } catch (Exception ex) { OnExceptionThrownAsync(ex); response = null; } if (response == null) { response = query; query.IsQuery = false; query.ReturnCode = ReturnCode.ServerFailure; } int length = response.Encode(false, out buffer); #region Truncating DnsMessage message = response as DnsMessage; if (message != null) { int maxLength = 512; while (length > maxLength) { int savedLength = 0; if (message.AuthorityRecords.Count > 0) { for (int i = message.AuthorityRecords.Count - 1; i >= 0; i--) { savedLength += message.AuthorityRecords[i].MaximumLength; message.AuthorityRecords.RemoveAt(i); if ((length - savedLength) < maxLength) { break; } } message.IsTruncated = true; length = message.Encode(false, out buffer); continue; } if (message.AnswerRecords.Count > 0) { for (int i = message.AnswerRecords.Count - 1; i >= 0; i--) { savedLength += message.AnswerRecords[i].MaximumLength; message.AnswerRecords.RemoveAt(i); if ((length - savedLength) < maxLength) { break; } } message.IsTruncated = true; length = message.Encode(false, out buffer); continue; } if (message.Questions.Count > 0) { for (int i = message.Questions.Count - 1; i >= 0; i--) { savedLength += message.Questions[i].MaximumLength; message.Questions.RemoveAt(i); if ((length - savedLength) < maxLength) { break; } } message.IsTruncated = true; length = message.Encode(false, out buffer); } } } #endregion await _udpListener.SendAsync(buffer, length, receiveResult.RemoteEndPoint); } catch (Exception ex) { OnExceptionThrownAsync(ex); } finally { lock (_listenerLock) { _availableUdpListener++; } StartUdpListenerTask(); } }
/// <summary> /// Sends an <see cref="ISnmpMessage"/> and handles the response from agent. /// </summary> /// <param name="request">The <see cref="ISnmpMessage"/>.</param> /// <param name="receiver">Agent.</param> /// <param name="udpSocket">The UDP <see cref="Socket"/> to use to send/receive.</param> /// <param name="registry">The user registry.</param> /// <returns></returns> public static async Task <ISnmpMessage> GetResponseAsync(this ISnmpMessage request, int timeout, IPEndPoint receiver, UserRegistry registry, UdpClient udpSocket, CancellationToken cancellationToken = default) { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (udpSocket == null) { throw new ArgumentNullException(nameof(udpSocket)); } if (registry == null) { throw new ArgumentNullException(nameof(registry)); } var requestCode = request.TypeCode(); if (requestCode == SnmpType.TrapV1Pdu || requestCode == SnmpType.TrapV2Pdu || requestCode == SnmpType.ReportPdu) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", requestCode)); } var bytes = request.ToBytes(); UdpReceiveResult result; udpSocket.Connect(receiver); var recvTask = udpSocket.ReceiveAsync(); if (timeout > 0) { var timeoutTask = Task.Delay(timeout, cancellationToken); await udpSocket.SendAsync(bytes, bytes.Length).ConfigureAwait(false); var r = await Task.WhenAny(new Task[] { recvTask, timeoutTask }).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); if (r == timeoutTask) { udpSocket.Close(); throw TimeoutException.Create(receiver.Address, timeout); } } result = await recvTask.ConfigureAwait(false); // Passing 'count' is not necessary because ParseMessages should ignore it, but it offer extra safety (and would avoid an issue if parsing >1 response). var response = MessageFactory.ParseMessages(result.Buffer, 0, result.Buffer.Length, registry)[0]; var responseCode = response.TypeCode(); if (responseCode == SnmpType.ResponsePdu || responseCode == SnmpType.ReportPdu) { var requestId = request.MessageId(); var responseId = response.MessageId(); if (responseId != requestId) { throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response sequence: expected {0}, received {1}", requestId, responseId), receiver.Address); } return(response); } throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response type: {0}", responseCode), receiver.Address); }
private async Task SendVoiceAsync(CancellationToken cancelToken) { try { while (!cancelToken.IsCancellationRequested && State != ConnectionState.Connected) { await Task.Delay(1).ConfigureAwait(false); } if (cancelToken.IsCancellationRequested) { return; } byte[] frame = new byte[_encoder.FrameSize]; byte[] encodedFrame = new byte[MaxOpusSize]; byte[] voicePacket, pingPacket, nonce = null; uint timestamp = 0; double nextTicks = 0.0, nextPingTicks = 0.0; long ticksPerSeconds = Stopwatch.Frequency; double ticksPerMillisecond = Stopwatch.Frequency / 1000.0; double ticksPerFrame = ticksPerMillisecond * _encoder.FrameLength; double spinLockThreshold = 3 * ticksPerMillisecond; uint samplesPerFrame = (uint)_encoder.SamplesPerFrame; Stopwatch sw = Stopwatch.StartNew(); if (_isEncrypted) { nonce = new byte[24]; voicePacket = new byte[MaxOpusSize + 12 + 16]; } else { voicePacket = new byte[MaxOpusSize + 12]; } pingPacket = new byte[8]; int rtpPacketLength = 0; voicePacket[0] = 0x80; //Flags; voicePacket[1] = 0x78; //Payload Type voicePacket[8] = (byte)(_ssrc >> 24); voicePacket[9] = (byte)(_ssrc >> 16); voicePacket[10] = (byte)(_ssrc >> 8); voicePacket[11] = (byte)(_ssrc >> 0); if (_isEncrypted) { Buffer.BlockCopy(voicePacket, 0, nonce, 0, 12); } bool hasFrame = false; while (!cancelToken.IsCancellationRequested) { if (!hasFrame && _sendBuffer.Pop(frame) && frame.Length == _encoder.SamplesPerFrame * _encoder.SampleSize) { ushort sequence = unchecked (_sequence++); voicePacket[2] = (byte)(sequence >> 8); voicePacket[3] = (byte)(sequence >> 0); voicePacket[4] = (byte)(timestamp >> 24); voicePacket[5] = (byte)(timestamp >> 16); voicePacket[6] = (byte)(timestamp >> 8); voicePacket[7] = (byte)(timestamp >> 0); Console.WriteLine("Test: " + frame.Length + ", " + encodedFrame.Length); //Encode int encodedLength = _encoder.EncodeFrame(frame, 0, encodedFrame); Console.WriteLine("Bammo!"); if (encodedLength > 0) { //Encrypt if (_isEncrypted) { Buffer.BlockCopy(voicePacket, 2, nonce, 2, 6); //Update nonce int ret = SecretBox.Encrypt(encodedFrame, encodedLength, voicePacket, 12, nonce, _secretKey); if (ret != 0) { continue; } rtpPacketLength = encodedLength + 12 + 16; } else { Buffer.BlockCopy(encodedFrame, 0, voicePacket, 12, encodedLength); rtpPacketLength = encodedLength + 12; } Console.WriteLine("++Send: " + sequence + ", " + timestamp + ", " + rtpPacketLength); timestamp = unchecked (timestamp + samplesPerFrame); hasFrame = true; } } long currentTicks = sw.ElapsedTicks; double ticksToNextFrame = nextTicks - currentTicks; if (ticksToNextFrame <= 0.0) { if (hasFrame) { try { await _udp.SendAsync(voicePacket, rtpPacketLength, _endpoint).ConfigureAwait(false); } catch (SocketException ex) { Logger.Error("Failed to send UDP packet.", ex); } hasFrame = false; } nextTicks += ticksPerFrame; //Is it time to send out another ping? if (currentTicks > nextPingTicks) { //Increment in LE for (int i = 0; i < 8; i++) { var b = pingPacket[i]; if (b == byte.MaxValue) { pingPacket[i] = 0; } else { pingPacket[i] = (byte)(b + 1); break; } } await _udp.SendAsync(pingPacket, pingPacket.Length, _endpoint).ConfigureAwait(false); nextPingTicks = currentTicks + 5 * ticksPerSeconds; } } else { if (hasFrame) { int time = (int)Math.Floor(ticksToNextFrame / ticksPerMillisecond); if (time > 0) { await Task.Delay(time).ConfigureAwait(false); } } else { await Task.Delay(1).ConfigureAwait(false); //Give as much time to the encrypter as possible } } } } catch (Exception ex) { Logger.Error(ex); } }
public async Task <IResponse> Resolve(IRequest request) { IResponse res = Response.FromRequest(request); var question = res.Questions[0]; IPEndPoint[] dnsS; if (_puredns != null) { dnsS = IsOnList(question.Name.ToString()) ? _updns : _puredns; } else { dnsS = _updns; } ClientResponse clientResponse = null; foreach (var dns in dnsS) { using (var udp = new UdpClient()) { UdpReceiveResult result; try { await udp.SendAsync(request.ToArray(), request.Size, dns).WithCancellationTimeout(Timeout); result = await udp.ReceiveAsync().WithCancellationTimeout(Timeout); } catch { Console.WriteLine($@"DNS query timeout via {dns}"); continue; } if (!result.RemoteEndPoint.Equals(dns)) { throw new IOException(@"Remote endpoint mismatch"); } var buffer = result.Buffer; var response = Response.FromArray(buffer); if (response.Truncated) { return(await new NullRequestResolver().Resolve(request)); } clientResponse = new ClientResponse(request, response, buffer); var records = clientResponse.AnswerRecords; var noanswer = OutputLog(records, question.Name, dns); if (!noanswer) { return(clientResponse); } } } if (clientResponse == null) { Console.WriteLine(@"All DNS Servers response timeout!"); throw new IOException(@"All DNS Servers response timeout!"); } return(clientResponse); }
static async Task SendWakeOnLan(IPAddress localIpAddress, IPAddress multicastIpAddress, byte[] magicPacket) { Console.WriteLine($"{DateTime.Now}--Try Wake-up {localIpAddress}."); using UdpClient client = new UdpClient(new IPEndPoint(localIpAddress, 0)); await client.SendAsync(magicPacket, magicPacket.Length, multicastIpAddress.ToString(), 9); }