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


C# Socket.AcceptAsync方法代码示例

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


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

示例1: ReuseSocketAsyncEventArgs_SameInstance_MultipleSockets

        public async Task ReuseSocketAsyncEventArgs_SameInstance_MultipleSockets()
        {
            using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                listen.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                listen.Listen(1);

                Task<Socket> acceptTask = listen.AcceptAsync();
                await Task.WhenAll(
                    acceptTask,
                    client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port)));

                using (Socket server = await acceptTask)
                {
                    TaskCompletionSource<bool> tcs = null;

                    var args = new SocketAsyncEventArgs();
                    args.SetBuffer(new byte[1024], 0, 1024);
                    args.Completed += (_,__) => tcs.SetResult(true);

                    for (int i = 1; i <= 10; i++)
                    {
                        tcs = new TaskCompletionSource<bool>();
                        args.Buffer[0] = (byte)i;
                        args.SetBuffer(0, 1);
                        if (server.SendAsync(args))
                        {
                            await tcs.Task;
                        }

                        args.Buffer[0] = 0;
                        tcs = new TaskCompletionSource<bool>();
                        if (client.ReceiveAsync(args))
                        {
                            await tcs.Task;
                        }
                        Assert.Equal(1, args.BytesTransferred);
                        Assert.Equal(i, args.Buffer[0]);
                    }
                }
            }
        }
开发者ID:dotnet,项目名称:corefx,代码行数:43,代码来源:SocketAsyncEventArgsTest.cs

示例2: 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

示例3: AcceptAsync_IpV4_Success

        public void AcceptAsync_IpV4_Success()
        {
            Assert.True(Capability.IPv4Support());

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

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

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

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

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

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

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

示例4: AcceptAsync_NotListening_Throws_InvalidOperation

 public void AcceptAsync_NotListening_Throws_InvalidOperation()
 {
     using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
     {
         socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
         Assert.Throws<InvalidOperationException>(() => socket.AcceptAsync(s_eventArgs));
     }
 }
开发者ID:nbilling,项目名称:corefx,代码行数:8,代码来源:ArgumentValidationTests.cs

示例5: PollWrite_Single_Timeout

        public void PollWrite_Single_Timeout()
        {
            using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                listener.BindToAnonymousPort(IPAddress.Loopback);
                listener.Listen(1);
                listener.AcceptAsync();

                Assert.False(listener.Poll(SelectTimeout, SelectMode.SelectWrite));
            }
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:11,代码来源:SelectAndPollTests.cs

示例6: SelectWrite_Multiple_Mixed

        public void SelectWrite_Multiple_Mixed()
        {
            using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                listener.BindToAnonymousPort(IPAddress.Loopback);
                listener.Listen(1);
                listener.AcceptAsync();

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

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

示例7: SelectWrite_Multiple_Timeout

        public void SelectWrite_Multiple_Timeout()
        {
            using (var firstListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            using (var secondListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                firstListener.BindToAnonymousPort(IPAddress.Loopback);
                firstListener.Listen(1);
                firstListener.AcceptAsync();
                
                secondListener.BindToAnonymousPort(IPAddress.Loopback);
                secondListener.Listen(1);
                secondListener.AcceptAsync();

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

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

示例8: Socket_Connect_IPv4AddressAsStringHost_Supported

        public async Task Socket_Connect_IPv4AddressAsStringHost_Supported()
        {
            using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                host.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                host.Listen(1);
                Task accept = host.AcceptAsync();

                using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    s.Connect(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port);
                }

                await accept;
            }
        }
开发者ID:shmao,项目名称:corefx,代码行数:16,代码来源:ArgumentValidationTests.cs

示例9: SendRecvAsync_Stream_TCP

        public void SendRecvAsync_Stream_TCP(IPAddress listenAt, bool useMultipleBuffers)
        {
            const int BytesToSend = 123456;
            const int ListenBacklog = 1;
            const int LingerTime = 60;
            const int TestTimeout = 30000;

            var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            server.BindToAnonymousPort(listenAt);

            server.Listen(ListenBacklog);

            var serverFinished = new TaskCompletionSource<bool>();
            int bytesReceived = 0;
            var receivedChecksum = new Fletcher32();

            var serverEventArgs = new SocketAsyncEventArgs();
            server.AcceptAsync(serverEventArgs, remote =>
            {
                Action<int> recvHandler = null;
                bool first = true;

                if (!useMultipleBuffers)
                {
                    var recvBuffer = new byte[256];
                    recvHandler = received => 
                    {
                        if (!first)
                        {
                            if (received == 0)
                            {
                                remote.Dispose();
                                server.Dispose();
                                serverFinished.SetResult(true);
                                return;
                            }

                            bytesReceived += received;
                            receivedChecksum.Add(recvBuffer, 0, received);
                        }
                        else
                        {
                            first = false;
                        }

                        remote.ReceiveAsync(serverEventArgs, recvBuffer, 0, recvBuffer.Length, SocketFlags.None, recvHandler);
                    };
                }
                else
                {
                    var recvBuffers = new List<ArraySegment<byte>> {
                        new ArraySegment<byte>(new byte[123]),
                        new ArraySegment<byte>(new byte[256], 2, 100),
                        new ArraySegment<byte>(new byte[1], 0, 0),
                        new ArraySegment<byte>(new byte[64], 9, 33)
                    };

                    recvHandler = received =>
                    {
                        if (!first)
                        {
                            if (received == 0)
                            {
                                remote.Dispose();
                                server.Dispose();
                                serverFinished.SetResult(true);
                                return;
                            }

                            bytesReceived += received;
                            for (int i = 0, remaining = received; i < recvBuffers.Count && remaining > 0; i++)
                            {
                                ArraySegment<byte> buffer = recvBuffers[i];
                                int toAdd = Math.Min(buffer.Count, remaining);
                                receivedChecksum.Add(buffer.Array, buffer.Offset, toAdd);
                                remaining -= toAdd;
                            }
                        }
                        else
                        {
                            first = false;
                        }

                        remote.ReceiveAsync(serverEventArgs, recvBuffers, SocketFlags.None, recvHandler);
                    };
                }

                recvHandler(0);
            });

            EndPoint clientEndpoint = server.LocalEndPoint;
            var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            int bytesSent = 0;
            var sentChecksum = new Fletcher32();

            var clientEventArgs = new SocketAsyncEventArgs();
            client.ConnectAsync(clientEventArgs, clientEndpoint, () =>
            {
                Action<int> sendHandler = null;
//.........这里部分代码省略.........
开发者ID:ChuangYang,项目名称:corefx,代码行数:101,代码来源:SendReceive.cs

示例10: ConcurrentSendReceive

        public void ConcurrentSendReceive()
        {
            using (Socket server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
            using (Socket client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
            {
                const int Iters = 2048;
                byte[] sendData = new byte[Iters];
                byte[] receiveData = new byte[sendData.Length];
                new Random().NextBytes(sendData);

                string path = GetRandomNonExistingFilePath();

                server.Bind(new UnixDomainSocketEndPoint(path));
                server.Listen(1);

                Task<Socket> acceptTask = server.AcceptAsync();
                client.Connect(new UnixDomainSocketEndPoint(path));
                acceptTask.Wait();
                Socket accepted = acceptTask.Result;

                Task[] writes = new Task[Iters];
                Task<int>[] reads = new Task<int>[Iters];
                for (int i = 0; i < Iters; i++)
                {
                    writes[i] = client.SendAsync(new ArraySegment<byte>(sendData, i, 1), SocketFlags.None);
                }
                for (int i = 0; i < Iters; i++)
                {
                    reads[i] = accepted.ReceiveAsync(new ArraySegment<byte>(receiveData, i, 1), SocketFlags.None);
                }
                Task.WaitAll(writes);
                Task.WaitAll(reads);

                Assert.Equal(sendData, receiveData);
            }
        }
开发者ID:ChuangYang,项目名称:corefx,代码行数:36,代码来源:UnixDomainSocketTest.cs

示例11: Socket_SendReceiveAsync_Success

        public async Task Socket_SendReceiveAsync_Success()
        {
            string path = GetRandomNonExistingFilePath();
            var endPoint = new UnixDomainSocketEndPoint(path);
            try
            {
                using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                {
                    server.Bind(endPoint);
                    server.Listen(1);

                    await client.ConnectAsync(endPoint);
                    using (Socket accepted = await server.AcceptAsync())
                    {
                        var data = new byte[1];
                        for (int i = 0; i < 10; i++)
                        {
                            data[0] = (byte)i;

                            await accepted.SendAsync(new ArraySegment<byte>(data), SocketFlags.None);
                            data[0] = 0;

                            Assert.Equal(1, await client.ReceiveAsync(new ArraySegment<byte>(data), SocketFlags.None));
                            Assert.Equal(i, data[0]);
                        }
                    }
                }
            }
            finally
            {
                try { File.Delete(path); }
                catch { }
            }
        }
开发者ID:ChuangYang,项目名称:corefx,代码行数:35,代码来源:UnixDomainSocketTest.cs

示例12: CreateConnectedSockets

        private static KeyValuePair<Socket, Socket> CreateConnectedSockets()
        {
            using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                listener.LingerState = new LingerOption(true, 0);
                listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                listener.Listen(1);

                Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                client.LingerState = new LingerOption(true, 0);

                Task<Socket> acceptTask = listener.AcceptAsync();
                client.Connect(listener.LocalEndPoint);
                Socket server = acceptTask.GetAwaiter().GetResult();

                return new KeyValuePair<Socket, Socket>(client, server);
            }
        }
开发者ID:ChuangYang,项目名称:corefx,代码行数:18,代码来源:SelectTest.cs

示例13: Socket_ConnectAsync_IPv6AddressAsStringHost_Supported

        public async Task Socket_ConnectAsync_IPv6AddressAsStringHost_Supported()
        {
            using (Socket host = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
            {
                host.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0));
                host.Listen(1);

                using (Socket s = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
                {
                    await Task.WhenAll(
                        host.AcceptAsync(),
                        s.ConnectAsync(IPAddress.IPv6Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port));
                }
            }
        }
开发者ID:shmao,项目名称:corefx,代码行数:15,代码来源:ArgumentValidationTests.cs

示例14: DualModeConnect_AcceptAsync_Helper

        private void DualModeConnect_AcceptAsync_Helper(IPAddress listenOn, IPAddress connectTo)
        {
            using (Socket serverSocket = new Socket(SocketType.Stream, ProtocolType.Tcp))
            {
                int port = serverSocket.BindToAnonymousPort(listenOn);
                serverSocket.Listen(1);

                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.Completed += AsyncCompleted;
                ManualResetEvent waitHandle = new ManualResetEvent(false);
                args.UserToken = waitHandle;

                _log.WriteLine(args.GetHashCode() + " SocketAsyncEventArgs with manual event " + waitHandle.GetHashCode());

                serverSocket.AcceptAsync(args);
                SocketClient client = new SocketClient(serverSocket, connectTo, port);
                Assert.True(waitHandle.WaitOne(Configuration.PassingTestTimeout), "Timed out while waiting for connection");

                if (args.SocketError != SocketError.Success)
                {
                    throw new SocketException((int)args.SocketError);
                }

                Socket clientSocket = args.AcceptSocket;
                Assert.NotNull(clientSocket);
                Assert.True(clientSocket.Connected);
                Assert.True(clientSocket.DualMode);
                Assert.Equal(AddressFamily.InterNetworkV6, clientSocket.AddressFamily);
                Assert.Equal(connectTo.MapToIPv6(), ((IPEndPoint)clientSocket.LocalEndPoint).Address);
            }
        }
开发者ID:rainersigwald,项目名称:corefx,代码行数:31,代码来源:DualModeSocketTest.cs

示例15: AcceptAsync_WithReceiveBuffer_Success

        public void AcceptAsync_WithReceiveBuffer_Success()
        {
            Assert.True(Capability.IPv4Support());

            AutoResetEvent accepted = new AutoResetEvent(false);

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

                const int acceptBufferOverheadSize = 288; // see https://msdn.microsoft.com/en-us/library/system.net.sockets.socket.acceptasync(v=vs.110).aspx
                const int acceptBufferDataSize = 256;
                const int acceptBufferSize = acceptBufferOverheadSize + acceptBufferDataSize;

                byte[] sendBuffer = new byte[acceptBufferDataSize];
                new Random().NextBytes(sendBuffer);

                SocketAsyncEventArgs acceptArgs = new SocketAsyncEventArgs();
                acceptArgs.Completed += OnAcceptCompleted;
                acceptArgs.UserToken = accepted;
                acceptArgs.SetBuffer(new byte[acceptBufferSize], 0, acceptBufferSize);

                Assert.True(server.AcceptAsync(acceptArgs));
                _log.WriteLine("IPv4 Server: Waiting for clients.");

                using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    client.Connect(IPAddress.Loopback, port);
                    client.Send(sendBuffer);
                    client.Shutdown(SocketShutdown.Both);
                }

                Assert.True(
                    accepted.WaitOne(Configuration.PassingTestTimeout), "Test completed in alotted time");

                Assert.Equal(
                    SocketError.Success, acceptArgs.SocketError);

                Assert.Equal(
                    acceptBufferDataSize, acceptArgs.BytesTransferred);

                Assert.Equal(
                    new ArraySegment<byte>(sendBuffer), 
                    new ArraySegment<byte>(acceptArgs.Buffer, 0, acceptArgs.BytesTransferred));
            }
        }
开发者ID:SGuyGe,项目名称:corefx,代码行数:47,代码来源:AcceptAsync.cs


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