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


C# Socket.BindToAnonymousPort方法代码示例

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


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

示例1: Success

        public void Success()
        {
            ManualResetEvent completed = new ManualResetEvent(false);

            if (Socket.OSSupportsIPv4)
            {
                using (Socket receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
                {
                    int port = receiver.BindToAnonymousPort(IPAddress.Loopback);
                    receiver.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);

                    Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    sender.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                    sender.SendTo(new byte[1024], new IPEndPoint(IPAddress.Loopback, port));

                    SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                    args.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    args.SetBuffer(new byte[1024], 0, 1024);
                    args.Completed += OnCompleted;
                    args.UserToken = completed;

                    Assert.True(receiver.ReceiveMessageFromAsync(args));

                    Assert.True(completed.WaitOne(Configuration.PassingTestTimeout), "Timeout while waiting for connection");

                    Assert.Equal(1024, args.BytesTransferred);
                    Assert.Equal(sender.LocalEndPoint, args.RemoteEndPoint);
                    Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, args.ReceiveMessageFromPacketInfo.Address);

                    sender.Dispose();
                }
            }
        }
开发者ID:rainersigwald,项目名称:corefx,代码行数:33,代码来源:ReceiveMessageFromAsync.cs

示例2: Success

        public void Success()
        {
            if (Socket.OSSupportsIPv4)
            {
                using (Socket receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
                {
                    int port = receiver.BindToAnonymousPort(IPAddress.Loopback);
                    receiver.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);

                    Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    sender.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                    sender.SendTo(new byte[1024], new IPEndPoint(IPAddress.Loopback, port));

                    IPPacketInformation packetInformation;
                    SocketFlags flags = SocketFlags.None;
                    EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);

                    int len = receiver.ReceiveMessageFrom(new byte[1024], 0, 1024, ref flags, ref remoteEP, out packetInformation);

                    Assert.Equal(1024, len);
                    Assert.Equal(sender.LocalEndPoint, remoteEP);
                    Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, packetInformation.Address);

                    sender.Dispose();
                }
            }
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:27,代码来源:ReceiveMessageFrom.cs

示例3: GetNonDefaultIPPacketInformation

        private IPPacketInformation GetNonDefaultIPPacketInformation()
        {
            const int ReceiveTimeout = 5000;

            using (var receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                int port = receiver.BindToAnonymousPort(IPAddress.Loopback);

                var waitHandle = new ManualResetEvent(false);

                SocketAsyncEventArgs receiveArgs = new SocketAsyncEventArgs {
                    RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port),
                    UserToken = waitHandle
                };

                receiveArgs.SetBuffer(new byte[1], 0, 1);
                receiveArgs.Completed += (_, args) => ((ManualResetEvent)args.UserToken).Set();

                Assert.True(receiver.ReceiveMessageFromAsync(receiveArgs));

                // Send a few packets, in case they aren't delivered reliably.
                for (int i = 0; i < Configuration.UDPRedundancy; i++)
                {
                    sender.SendTo(new byte[1], new IPEndPoint(IPAddress.Loopback, port));
                }

                Assert.True(waitHandle.WaitOne(ReceiveTimeout));

                return receiveArgs.ReceiveMessageFromPacketInfo;
            }
        }
开发者ID:SGuyGe,项目名称:corefx,代码行数:32,代码来源:IPPacketInformationTest.cs

示例4: SelectRead_Multiple_Success

        public void SelectRead_Multiple_Success()
        {
            using (var firstReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            using (var secondReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                int firstReceiverPort = firstReceiver.BindToAnonymousPort(IPAddress.Loopback);
                var firstReceiverEndpoint = new IPEndPoint(IPAddress.Loopback, firstReceiverPort);

                int secondReceiverPort = secondReceiver.BindToAnonymousPort(IPAddress.Loopback);
                var secondReceiverEndpoint = new IPEndPoint(IPAddress.Loopback, secondReceiverPort);

                sender.SendTo(new byte[1], SocketFlags.None, firstReceiverEndpoint);
                sender.SendTo(new byte[1], SocketFlags.None, secondReceiverEndpoint);

                var sw = Stopwatch.StartNew();
                Assert.True(SpinWait.SpinUntil(() =>
                {
                    var list = new List<Socket> { firstReceiver, secondReceiver };
                    Socket.Select(list, null, null, Math.Max((int)(SelectSuccessTimeoutMicroseconds - (sw.Elapsed.TotalSeconds * 1000000)), 0));
                    Assert.True(list.Count <= 2);
                    if (list.Count == 2)
                    {
                        Assert.Equal(firstReceiver, list[0]);
                        Assert.Equal(secondReceiver, list[1]);
                        return true;
                    }
                    return false;
                }, SelectSuccessTimeoutMicroseconds / 1000), "Failed to select both items within allotted time");
            }
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:31,代码来源:SelectAndPollTests.cs

示例5: ReceiveTimesOut_Throws

        public void ReceiveTimesOut_Throws()
        {
            using (Socket localSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
            {
                using (Socket remoteSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
                {
                    int port = localSocket.BindToAnonymousPort(IPAddress.IPv6Loopback);
                    localSocket.Listen(1);
                    IAsyncResult localAsync = localSocket.BeginAccept(null, null);

                    remoteSocket.Connect(IPAddress.IPv6Loopback, port);

                    Socket acceptedSocket = localSocket.EndAccept(localAsync);
                    acceptedSocket.ReceiveTimeout = 100;

                    SocketException sockEx = Assert.Throws<SocketException>(() =>
                   {
                       acceptedSocket.Receive(new byte[1]);
                   });

                    Assert.Equal(SocketError.TimedOut, sockEx.SocketErrorCode);
                    Assert.True(acceptedSocket.Connected);
                }
            }
        }
开发者ID:fuwei199006,项目名称:corefx,代码行数:25,代码来源:TimeoutTest.cs

示例6: GetNonDefaultIPPacketInformation

        private IPPacketInformation GetNonDefaultIPPacketInformation()
        {
            const int ReceiveTimeout = 5000;

            using (var receiver = new Socket(SocketType.Dgram, ProtocolType.Udp))
            using (var sender = new Socket(SocketType.Dgram, ProtocolType.Udp))
            {
                int port = receiver.BindToAnonymousPort(IPAddress.Loopback);

                var waitHandle = new ManualResetEvent(false);

                SocketAsyncEventArgs receiveArgs = new SocketAsyncEventArgs {
                    RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port),
                    UserToken = waitHandle
                };

                receiveArgs.SetBuffer(new byte[1], 0, 1);
                receiveArgs.Completed += (_, args) => ((ManualResetEvent)args.UserToken).Set();

                Assert.True(receiver.ReceiveMessageFromAsync(receiveArgs));

                sender.SendTo(new byte[1], new IPEndPoint(IPAddress.Loopback, port));

                Assert.True(waitHandle.WaitOne(ReceiveTimeout));

                return receiveArgs.ReceiveMessageFromPacketInfo;
            }
        }
开发者ID:vbouret,项目名称:corefx,代码行数:28,代码来源:IPPacketInformationTest.cs

示例7: SelectRead_Single_Timeout

        public void SelectRead_Single_Timeout()
        {
            using (var receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                receiver.BindToAnonymousPort(IPAddress.Loopback);

                var list = new List<Socket> { receiver };
                Socket.Select(list, null, null, SelectTimeout);

                Assert.Equal(0, list.Count);
            }
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:12,代码来源:SelectAndPollTests.cs

示例8: Socket_ReceiveFromDnsEndPoint_ArgumentException

        public void Socket_ReceiveFromDnsEndPoint_ArgumentException()
        {
            using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                int port = sock.BindToAnonymousPort(IPAddress.Loopback);
                EndPoint endpoint = new DnsEndPoint("localhost", port);

                Assert.Throws<ArgumentException>(() =>
                {
                    sock.ReceiveFrom(new byte[10], ref endpoint);
                });
            }
        }
开发者ID:nbilling,项目名称:corefx,代码行数:13,代码来源:DnsEndPointTest.cs

示例9: SelectRead_Single_Success

        public void SelectRead_Single_Success()
        {
            using (var receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                int receiverPort = receiver.BindToAnonymousPort(IPAddress.Loopback);
                var receiverEndpoint = new IPEndPoint(IPAddress.Loopback, receiverPort);

                sender.SendTo(new byte[1], SocketFlags.None, receiverEndpoint);

                var list = new List<Socket> { receiver };
                Socket.Select(list, null, null, SelectSuccessTimeoutMicroseconds);

                Assert.Equal(1, list.Count);
                Assert.Equal(receiver, list[0]);
            }
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:17,代码来源:SelectAndPollTests.cs

示例10: SetLingerAfterServerClosed

        public void SetLingerAfterServerClosed(bool linger, int timeout)
        {
            using (var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                int port = server.BindToAnonymousPort(IPAddress.Loopback);
                server.Listen(1);

                var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                {
                    client.Connect(IPAddress.Loopback, port);

                    server.Dispose();
                    Thread.Sleep(10); // give the server socket time to close

                    client.LingerState = new LingerOption(linger, timeout);
                }
            }
        }
开发者ID:ChuangYang,项目名称:corefx,代码行数:18,代码来源:LingerStateTest.cs

示例11: Shutdown_TCP_CLOSED_Success

        public void Shutdown_TCP_CLOSED_Success()
        {
            // NOTE: this value should technically be at least as long as the amount
            //       of time that a TCP connection will stay in the TIME_WAIT state.
            //       That value, however, is technically defined as 2 * MSL, which is
            //       officially 4 minutes, and may differ between systems. In practice,
            //       5 seconds has proved to be long enough.
            const int TimeWaitTimeout = 5000;

            using (Socket server = new Socket(SocketType.Stream, ProtocolType.Tcp))
            using (Socket client = new Socket(SocketType.Stream, ProtocolType.Tcp))
            {
                int port = server.BindToAnonymousPort(IPAddress.IPv6Any);
                server.Listen(1);

                var args = new SocketAsyncEventArgs();
                args.Completed += OnOperationCompleted;
                Assert.True(server.AcceptAsync(args));

                client.Connect(IPAddress.IPv6Loopback, port);

                var buffer = new byte[] { 42 };
                for (int i = 0; i < 32; i++)
                {
                    int sent = client.Send(buffer);
                    Assert.Equal(1, sent);
                }

                client.Shutdown(SocketShutdown.Send);

                int received = 0;
                do
                {
                    received = client.Receive(buffer);
                } while (received != 0);

                // Wait for the underlying connection to transition from TIME_WAIT to
                // CLOSED.
                Task.Delay(TimeWaitTimeout).Wait();

                client.Shutdown(SocketShutdown.Both);
            }
        }
开发者ID:nnyamhon,项目名称:corefx,代码行数:43,代码来源:Shutdown.cs

示例12: SocketSendTimeout_Send_Success

        public void SocketSendTimeout_Send_Success()
        {
            using (Socket localSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
            {
                using (Socket remoteSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
                {
                    int port = localSocket.BindToAnonymousPort(IPAddress.IPv6Loopback);
                    localSocket.Listen(1);
                    IAsyncResult localAsync = localSocket.BeginAccept(null, null);

                    remoteSocket.Connect(IPAddress.IPv6Loopback, port);

                    Socket acceptedSocket = localSocket.EndAccept(localAsync);
                    acceptedSocket.SendTimeout = 100;

                    // Note that Send almost never times out because it only has to copy the data to the native buffer.
                    int bytes = acceptedSocket.Send(new byte[100]);
                    Assert.Equal(100, bytes);
                    Assert.True(acceptedSocket.Connected);
                }
            }
        }
开发者ID:fuwei199006,项目名称:corefx,代码行数:22,代码来源:TimeoutTest.cs

示例13: AcceptAsync_IPv6_Success

        public void AcceptAsync_IPv6_Success()
        {
            Assert.True(Capability.IPv6Support());

            AutoResetEvent completed = new AutoResetEvent(false);
            AutoResetEvent completedClient = new AutoResetEvent(false);

            using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
            {
                int port = sock.BindToAnonymousPort(IPAddress.IPv6Loopback);
                sock.Listen(1);

                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.Completed += OnAcceptCompleted;
                args.UserToken = completed;

                Assert.True(sock.AcceptAsync(args));
                _log.WriteLine("IPv6 Server: Waiting for clients.");

                using (Socket client = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
                {
                    SocketAsyncEventArgs argsClient = new SocketAsyncEventArgs();
                    argsClient.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, port);
                    argsClient.Completed += OnConnectCompleted;
                    argsClient.UserToken = completedClient;
                    client.ConnectAsync(argsClient);

                    _log.WriteLine("IPv6 Client: Connecting.");
                    Assert.True(completed.WaitOne(5000), "IPv6: Timed out while waiting for connection");

                    Assert.Equal<SocketError>(SocketError.Success, args.SocketError);
                    Assert.NotNull(args.AcceptSocket);
                    Assert.True(args.AcceptSocket.Connected, "IPv6 Accept Socket was not connected");
                    Assert.NotNull(args.AcceptSocket.RemoteEndPoint);
                    Assert.Equal(client.LocalEndPoint, args.AcceptSocket.RemoteEndPoint);
                }
            }
        }
开发者ID:noahfalk,项目名称:corefx,代码行数:38,代码来源:AcceptAsync.cs

示例14: SelectRead_Multiple_Success

        public void SelectRead_Multiple_Success()
        {
            using (var firstReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            using (var secondReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                int firstReceiverPort = firstReceiver.BindToAnonymousPort(IPAddress.Loopback);
                var firstReceiverEndpoint = new IPEndPoint(IPAddress.Loopback, firstReceiverPort);

                int secondReceiverPort = secondReceiver.BindToAnonymousPort(IPAddress.Loopback);
                var secondReceiverEndpoint = new IPEndPoint(IPAddress.Loopback, secondReceiverPort);

                sender.SendTo(new byte[1], SocketFlags.None, firstReceiverEndpoint);
                sender.SendTo(new byte[1], SocketFlags.None, secondReceiverEndpoint);

                var list = new List<Socket> { firstReceiver, secondReceiver };
                Socket.Select(list, null, null, SelectSuccessTimeout);

                Assert.Equal(2, list.Count);
                Assert.Equal(firstReceiver, list[0]);
                Assert.Equal(secondReceiver, list[1]);
            }
        }
开发者ID:natemcmaster,项目名称:corefx,代码行数:23,代码来源:SelectAndPollTests.cs

示例15: BindV6IPEndPoint_Success

 public void BindV6IPEndPoint_Success()
 {
     using (Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp))
     {
         socket.BindToAnonymousPort(IPAddress.IPv6Loopback);
     }
 }
开发者ID:eerhardt,项目名称:corefx,代码行数:7,代码来源:DualModeSocketTest.cs


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