/// <summary> /// Broadcasts the probe to a specific IP address /// </summary> /// <param name="ipAddress">The IPv4 address to broadcast to</param> private async void BroadcastTo(string ipAddress) { Socket UDPSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) { EnableBroadcast = true, MulticastLoopback = false }; IPAddress IPAddress = IPAddress.Parse(ipAddress); UDPSocket.Bind(new IPEndPoint(IPAddress.Any, 0)); // send IPEndPoint RemoteEndPoint = new IPEndPoint(IPAddress, DiscoveryService.BroadcastPort); byte[] ProbeBytes = this.GetProbe(); UDPSocket.SendTo(ProbeBytes, RemoteEndPoint); // and listen try { CancellationTokenSource ListenToken = new CancellationTokenSource(TimeSpan.FromSeconds(5)); UDPSocket.ReceiveTimeout = 5000; EndPoint From = new IPEndPoint(0, 0); while (!ListenToken.IsCancellationRequested) { byte[] Buffer = new byte[255]; int Read = await Task.Factory.FromAsync( UDPSocket.BeginReceiveFrom( Buffer, 0, Buffer.Length, SocketFlags.None, ref From, null, null), (r) => UDPSocket.EndReceiveFrom(r, ref From)); if (Read <= 0) { break; } MemoryStream Stream = new MemoryStream(Buffer, 0, Read); Stream.Seek(0, SeekOrigin.Begin); ISCPPacket Packet = await ISCPPacket.Read(Stream); DiscoveredDevice Device = DiscoveredDevice.Parse(Packet.Message, From); if (this.DiscoveredMacs.Contains(Device.MacAddress)) { return; } this.DiscoveredMacs.Add(Device.MacAddress); this.DeviceFound?.Invoke(this, Device); } } finally { UDPSocket.Close(); } }
/// <summary> /// Callback for when a new packet is received. /// </summary> /// <param name="packet">The packet that was received</param> private void OnPacket(ISCPPacket packet) { string Command = packet.Message.Command; Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine($"{Command} {packet.Message.Parameters}"); Console.ForegroundColor = ConsoleColor.White; if (this.CommandEvents.ContainsKey(Command)) { this.CommandEvents[Command](packet); } }
public async Task SendCommandAsync(string command, string parameters) { if (this.NetworkStream == null) { throw new InvalidOperationException( "Can't send message before connecting. Did you call APIClient.ConnectAsync()?"); } ISCPPacket Packet = new ISCPPacket(new ISCPMessage(command, parameters)); byte[] WriteBytes = Packet.Serialize(); await this.NetworkStream.WriteAsync(WriteBytes, 0, WriteBytes.Length); }
/// <summary> /// Starts the packet read loop from the network stream /// </summary> private async void ReadLoop() { try { while (!this.ReadCancellationToken.Token.IsCancellationRequested && this.Client.Connected) { ISCPPacket Next = await ISCPPacket.Read(this.NetworkStream); this.OnPacket(Next); } } catch (OperationCanceledException) { // ignored } catch (IOException) { // ignored } }