Dispose() public method

public Dispose ( ) : void
return void
コード例 #1
0
 /// <summary>
 /// Disposable pattern
 /// </summary>
 /// <param name="disposing">flag</param>
 protected virtual void Dispose(bool disposing)
 {
     ReleaseUnmanagedResources();
     if (disposing)
     {
         _udpClient?.Dispose();
     }
 }
コード例 #2
0
 public void Close()
 {
     if (socketReceiveThread.IsAlive)
     {
         socketReceiveThread.Abort();
     }
     udpClient.Close();
     udpClient.Dispose();
 }
コード例 #3
0
 /// <summary>
 /// Disposable pattern
 /// </summary>
 /// <param name="disposing"></param>
 protected virtual void Dispose(bool disposing)
 {
     ReleaseUnmanagedResources();
     if (disposing)
     {
         _udpClient?.Dispose();
         _mutex?.Dispose();
         _receivedPackets?.Clear();
     }
 }
コード例 #4
0
        private void btnRecieve_Click(object sender, EventArgs e)
        {
            IPEndPoint host = new IPEndPoint(IPAddress.Any, 0);

            System.Net.Sockets.UdpClient client = new System.Net.Sockets.UdpClient(int.Parse(tbxPort.Text));
            byte[] message = client.Receive(ref host);

            tbxMessage.Text += DateTime.Now.ToString("h:mm:ss tt") + ": " + Encoding.Unicode.GetString(message);
            tbxMessage.Text += Environment.NewLine;

            client.Dispose();
        }
コード例 #5
0
        /// <summary>
        /// Stops listening for incoming connections
        /// </summary>
        public override void Stop()
        {
            if (!Running)
            {
                return;
            }
            System.Net.Sockets.UdpClient listener = this.listener;
            this.listener = null;
#if NETSTANDARD1_5
            listener.Dispose();
#else
            listener.Close();
#endif
        }
コード例 #6
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    sysClient.Dispose();
                    listener.Dispose();
                }

                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                // TODO: set large fields to null.

                disposedValue = true;
            }
        }
コード例 #7
0
ファイル: LunaUdp.cs プロジェクト: romanchom/Luna
 public LunaUdp()
 {
     byte[] hello = Encoding.ASCII.GetBytes("\u0001LunaDaemon");
     udp = new UdpClient(1234);
     udp.Client.ReceiveTimeout = 1000;
     IPEndPoint dst = new IPEndPoint(IPAddress.Broadcast, 1234);
     udp.Send(hello, hello.Length, dst);
     this.udp.Receive(ref dst);
     dst = new IPEndPoint(IPAddress.Any, 1234);
     try
     {
         hello = udp.Receive(ref dst);
     }
     catch
     {
         udp.Dispose();
         throw;
     }
     udp.Connect(dst);
     SendTurnOn();
 }
コード例 #8
0
        async Task NetworkRequestAsync(byte[] requestBytes,
                                              TimeSpan scanTime,
                                              int retries,
                                              int retryDelayMilliseconds,
                                              Action<string, 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

#if !XAMARIN
            if (!adapter.GetIPProperties().MulticastAddresses.Any())
                return; // most of VPN adapters will be skipped
#endif
            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++)
                {
#if ANDROID
                    var mlock = wifi.CreateMulticastLock("Zeroconf lock");
#endif
                    try
                    {
#if ANDROID
                        mlock.Acquire();
#endif
                        client.Client.SetSocketOption(SocketOptionLevel.IP,
                                                      SocketOptionName.MulticastInterface,
                                                      IPAddress.HostToNetworkOrder(ifaceIndex));



                        client.ExclusiveAddressUse = false;
                        client.Client.SetSocketOption(SocketOptionLevel.Socket,
                                                      SocketOptionName.ReuseAddress,
                                                      true);
                        client.Client.SetSocketOption(SocketOptionLevel.Socket,
                                                      SocketOptionName.ReceiveTimeout,
                                                      scanTime.Milliseconds);
                        client.ExclusiveAddressUse = false;

                        
                        var localEp = new IPEndPoint(IPAddress.Any, 5353);

                        Debug.WriteLine($"Attempting to bind to {localEp} on adapter {adapter.Name}");
                        client.Client.Bind(localEp);
                        Debug.WriteLine($"Bound to {localEp}");

                        var multicastAddress = IPAddress.Parse("224.0.0.251");
                        var multOpt = new MulticastOption(multicastAddress, ifaceIndex);
                        client.Client.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 (!shouldCancel)
                                                       {
                                                           var res = await client.ReceiveAsync()
                                                                                 .ConfigureAwait(false);
                                                           onResponse(res.RemoteEndPoint.Address.ToString(), res.Buffer);
                                                       }
                                                   }
                                                   catch (ObjectDisposedException)
                                                   {
                                                   }
                                               }, 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);
                        shouldCancel = true;
#if CORECLR
                        client.Dispose();
#else
                        client.Close();
#endif

                        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
                            throw;
                    }
                    finally
                    {
#if ANDROID
                        mlock.Release();
#endif
                    }

                    await Task.Delay(retryDelayMilliseconds, cancellationToken).ConfigureAwait(false);
                }
            }
        }
コード例 #9
0
 public void Dispose()
 {
     _client?.Dispose();
 }
コード例 #10
0
        public static void Send(this float[][] e, string hostname, int port)
        {
            var nicport = new Random().Next(16000, 40000);

            // https://twitter.com/ID_AA_Carmack/status/623585590848700416

            // X:\jsc.svn\examples\java\android\Test\TestUDPSend\TestUDPSend\ApplicationActivity.cs
            var socket = new UdpClient();
            // we assume we know our nic
            socket.Client.Bind(new IPEndPoint(IPAddress.Parse("192.168.1.12"), nicport));

            //var ElementSize = 4 * e[0].GetLength(0) * e[0].GetLength(1);
            var ElementSize = 4 * e[0].GetLength(0);

            var data64 = new byte[e.Length * ElementSize];

            for (int ei = 0; ei < e.Length; ei++)
            {

                //fixed (byte* output = data64)
                fixed (float* inputF = &e[ei][0])
                {
                    //Marshal.Copy(new IntPtr(p), new IntPtr(data), startIndex: 0, length: e.Length);
                    //Marshal.Copy(new IntPtr(p), data, startIndex: 0, length: e.Length);

                    var input8 = (byte*)inputF;

                    for (int i = 0; i < ElementSize; i++)
                    {
                        data64[i + ei * ElementSize] = input8[i];
                    }
                }
            }

            //var data64 = FloatArrayToByteArray(data);

            //         Unhandled Exception: System.Net.Sockets.SocketException: An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full
            //at System.Net.Sockets.Socket.SendTo(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, EndPoint remoteEP)
            //at System.Net.Sockets.UdpClient.Send(Byte[] dgram, Int32 bytes, String hostname, Int32 port)
            //at UDPWindWheel.x.Send(Single[][] e, String hostname, Int32 port) in x:\jsc.svn\examples\java\android\vr\OVRWindWheelNDK\UDPWindWheel\Program.cs:line 454
            //at UDPWindWheel.Program.Main(String[] args) in x:\jsc.svn\examples\java\android\vr\OVRWindWheelNDK\UDPWindWheel\Program.cs:line 409










            // can VR show our cube at the mat4 we are talking about?
            socket.Send(
                data64,
                data64.Length,
                hostname: hostname,
                port: port
            );

            socket.Dispose();
        }
コード例 #11
0
        Task ListenForAnnouncementsAsync(System.Net.NetworkInformation.NetworkInterface adapter, Action<AdapterInformation, string, byte[]> callback, CancellationToken cancellationToken)
        {
            return Task.Factory.StartNew(async () =>
            {
                var ipv4Address = adapter.GetIPProperties().UnicastAddresses
                                         .First(ua => ua.Address.AddressFamily == AddressFamily.InterNetwork)?.Address;

                if (ipv4Address == null)
                    return;

                var ifaceIndex = adapter.GetIPProperties().GetIPv4Properties()?.Index;
                if (ifaceIndex == null)
                    return;

                Debug.WriteLine($"Scanning on iface {adapter.Name}, idx {ifaceIndex}, IP: {ipv4Address}");

                using (var client = new UdpClient())
                {
#if ANDROID
                    var mlock = wifi.CreateMulticastLock("Zeroconf listen lock");
#endif
                    try
                    {
#if ANDROID
                        mlock.Acquire();
#endif
                        client.Client.SetSocketOption(SocketOptionLevel.IP,
                                                      SocketOptionName.MulticastInterface,
                                                      IPAddress.HostToNetworkOrder(ifaceIndex.Value));

                        client.Client.SetSocketOption(SocketOptionLevel.Socket,
                                                      SocketOptionName.ReuseAddress,
                                                      true);
                        client.ExclusiveAddressUse = false;


                        var localEp = new IPEndPoint(IPAddress.Any, 5353);
                        client.Client.Bind(localEp);

                        var multicastAddress = IPAddress.Parse("224.0.0.251");
                        var multOpt = new MulticastOption(multicastAddress, ifaceIndex.Value);
                        client.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multOpt);

                        while (!cancellationToken.IsCancellationRequested)
                        {
                            var packet = await client.ReceiveAsync().ConfigureAwait(false);
                            try
                            {
                                callback(new AdapterInformation(ipv4Address.ToString(), adapter.Name), packet.RemoteEndPoint.Address.ToString(), packet.Buffer);
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine($"Callback threw an exception: {ex}");
                            }
                        }

#if CORECLR
                        client.Dispose();
#else
                        client.Close();
#endif

                        Debug.WriteLine($"Done listening for mDNS packets on {adapter.Name}, idx {ifaceIndex}, IP: {ipv4Address}.");

                        cancellationToken.ThrowIfCancellationRequested();
                    }
                    finally
                    {
#if ANDROID
                    mlock.Release();
#endif
                    }
                }
            }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default).Unwrap();
        }