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


C# UdpClient.Dispose方法代码示例

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


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

示例1: LunaUdp

 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();
 }
开发者ID:romanchom,项目名称:Luna,代码行数:21,代码来源:LunaUdp.cs

示例2: NetworkRequestAsync

        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)
//.........这里部分代码省略.........
开发者ID:Lakritzator,项目名称:Zeroconf,代码行数:101,代码来源:NetworkInterface.cs

示例3: Send

        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();
        }
开发者ID:exaphaser,项目名称:JSC-Cross-Compiler,代码行数:61,代码来源:Program.cs

示例4: ListenForAnnouncementsAsync

        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();
        }
开发者ID:tingfangzheng,项目名称:Zeroconf,代码行数:75,代码来源:NetworkInterface.cs


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