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


C# SocketAsyncEventArgs.SetBuffer方法代码示例

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


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

示例1: DualModeSendToAsync_IPEndPointToHost_Helper

        private void DualModeSendToAsync_IPEndPointToHost_Helper(IPAddress connectTo, IPAddress listenOn, bool dualModeServer, bool expectedToTimeout = false)
        {
            int port;
            Socket client = new Socket(SocketType.Dgram, ProtocolType.Udp);
            using (SocketUdpServer server = new SocketUdpServer(_log, listenOn, dualModeServer, out port))
            {
                // Send a few packets, in case they aren't delivered reliably.
                for (int i = 0; i < Configuration.UDPRedundancy; i++)
                {
                    using (ManualResetEvent waitHandle = new ManualResetEvent(false))
                    {
                        SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                        args.RemoteEndPoint = new IPEndPoint(connectTo, port);
                        args.SetBuffer(new byte[1], 0, 1);
                        args.UserToken = waitHandle;
                        args.Completed += AsyncCompleted;

                        bool async = client.SendToAsync(args);
                        if (async)
                        {
                            Assert.True(waitHandle.WaitOne(Configuration.PassingTestTimeout), "Timeout while waiting for connection");
                        }

                        Assert.Equal(1, args.BytesTransferred);
                        if (args.SocketError != SocketError.Success)
                        {
                            throw new SocketException((int)args.SocketError);
                        }
                    }
                }

                bool success = server.WaitHandle.WaitOne(expectedToTimeout ? Configuration.FailingTestTimeout : Configuration.PassingTestTimeout); // Make sure the bytes were received
                if (!success)
                {
                    throw new TimeoutException();
                }
            }
        }
开发者ID:eerhardt,项目名称:corefx,代码行数:38,代码来源:DualModeSocketTest.cs

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

示例3: BeginRequestTime

		/// <summary>
		/// Connects to the server and begins listening for time updates.
		/// </summary>
		public void BeginRequestTime()
		{
			byte[] buffer = new byte[48];
			buffer[0] = 0x1B;
			for (var i = 1; i < buffer.Length; ++i)
			{
				buffer[i] = 0;
			}

			var endPoint = new DnsEndPoint(_ServerAddress, 123);

			_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
			var socketArgs = new SocketAsyncEventArgs() { RemoteEndPoint = endPoint };
			socketArgs.Completed += (o, e) =>
			{
				if (e.SocketError == SocketError.Success)
				{
					var sArgs = new SocketAsyncEventArgs()
					{
						RemoteEndPoint = endPoint
					};

					sArgs.Completed += new EventHandler<SocketAsyncEventArgs>(sArgs_Completed);
					sArgs.SetBuffer(buffer, 0, buffer.Length);
					sArgs.UserToken = buffer;
					_Socket.SendAsync(sArgs);
				}
			};
			_Socket.ConnectAsync(socketArgs);
		}
开发者ID:Yortw,项目名称:Yort.Ntp,代码行数:33,代码来源:NtpClient.cs

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

示例5: NewBuffer

            private SocketAsyncEventArgs NewBuffer()
            {
                SocketAsyncEventArgs e = new SocketAsyncEventArgs();
                e.SetBuffer(new byte[1024], 0, 1024);

                return e;
            }
开发者ID:lythm,项目名称:orb3d,代码行数:7,代码来源:BufferManager.cs

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

示例7: makeSocketAsyncEventArgs

 //生成自定义AsyncEventArg
 private SocketAsyncEventArgs makeSocketAsyncEventArgs()
 {
     SocketAsyncEventArgs re = new SocketAsyncEventArgs();
     re.UserToken = new AsyncUserToken(m_userTokenBufferLength);
     re.SetBuffer(((AsyncUserToken)re.UserToken).buffer, 0, m_userTokenBufferLength);
     re.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);
     return re;
 }
开发者ID:261521019,项目名称:CSharp-server,代码行数:9,代码来源:BaseSocket.cs

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

示例9: OnOperationCompleted

        private static void OnOperationCompleted(object sender, SocketAsyncEventArgs args)
        {
            Assert.Equal(SocketError.Success, args.SocketError);

            switch (args.LastOperation)
            {
                case SocketAsyncOperation.Accept:
                {
                    Socket client = args.AcceptSocket;
                    args.SetBuffer(new byte[1], 0, 1);
                    args.UserToken = client;

                    Assert.True(client.ReceiveAsync(args));
                    break;
                }

                case SocketAsyncOperation.Receive:
                {
                    var client = (Socket)args.UserToken;
                    if (args.BytesTransferred == 0)
                    {
                        client.Dispose();
                        break;
                    }

                    Assert.True(client.SendAsync(args));
                    break;
                }

                case SocketAsyncOperation.Send:
                {
                    var client = (Socket)args.UserToken;

                    Assert.True(args.BytesTransferred == args.Buffer.Length);
                    Assert.True(client.ReceiveAsync(args));
                    break;
                }
            }
        }
开发者ID:nnyamhon,项目名称:corefx,代码行数:39,代码来源:Shutdown.cs

示例10: ReceiveAsync

        public static void ReceiveAsync(this Socket socket, SocketAsyncEventArgs eventArgs, byte[] buffer, int offset, int count, SocketFlags flags, Action<int> handler)
        {
            EventHandler<SocketAsyncEventArgs> wrappedHandler = null;
            wrappedHandler = (_, args) =>
            {
                Assert.Equal(SocketError.Success, args.SocketError);

                int received = args.BytesTransferred;
                args.SetBuffer(null, 0, 0);
                args.SocketFlags = SocketFlags.None;
                args.Completed -= wrappedHandler;

                handler(received);
            };

            eventArgs.SetBuffer(buffer, offset, count);
            eventArgs.SocketFlags = flags;
            eventArgs.Completed += wrappedHandler;
            if (!socket.ReceiveAsync(eventArgs))
            {
                wrappedHandler(null, eventArgs);
            }
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:23,代码来源:SocketAsyncExtensions.cs

示例11: Socket_SendToAsyncDnsEndPoint_Throws

 [Fact] // Base case
 // "The parameter remoteEP must not be of type DnsEndPoint."
 public void Socket_SendToAsyncDnsEndPoint_Throws()
 {
     Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp);
     SocketAsyncEventArgs args = new SocketAsyncEventArgs();
     args.RemoteEndPoint = new DnsEndPoint("localhost", UnusedPort);
     args.SetBuffer(new byte[1], 0, 1);
     Assert.Throws<ArgumentException>(() =>
     {
         socket.SendToAsync(args);
     });
 }
开发者ID:eerhardt,项目名称:corefx,代码行数:13,代码来源:DualModeSocketTest.cs

示例12: Socket_SendToAsyncV4IPEndPointToV4Host_Throws

        [Fact] // Base case
        public void Socket_SendToAsyncV4IPEndPointToV4Host_Throws()
        {
            Socket socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
            SocketAsyncEventArgs args = new SocketAsyncEventArgs();
            args.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, UnusedPort);
            args.SetBuffer(new byte[1], 0, 1);
            bool async = socket.SendToAsync(args);
            Assert.False(async);

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                Assert.Equal(SocketError.Fault, args.SocketError);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                // NOTE: on Linux, this API returns ENETUNREACH instead of EFAULT: this platform
                //       checks the family of the provided socket address before checking its size
                //       (as long as the socket address is large enough to store an address family).
                Assert.Equal(SocketError.NetworkUnreachable, args.SocketError);
            }
            else
            {
                // NOTE: on other Unix platforms, this API returns EINVAL instead of EFAULT.
                Assert.Equal(SocketError.InvalidArgument, args.SocketError);
            }
        }
开发者ID:eerhardt,项目名称:corefx,代码行数:27,代码来源:DualModeSocketTest.cs

示例13: DoSend

        protected override void DoSend(byte[] bytes, int offset, int length, AsyncContinuation asyncContinuation)
        {
            lock (this)
            {
                var args = new SocketAsyncEventArgs();
                args.SetBuffer(bytes, offset, length);
                args.UserToken = asyncContinuation;
                args.Completed += this.SocketOperationCompleted;
                args.RemoteEndPoint = this.endpoint;

                if (!this.socket.SendToAsync(args))
                {
                    this.SocketOperationCompleted(this.socket, args);
                }
            }
        }
开发者ID:roji,项目名称:NLog,代码行数:16,代码来源:UdpNetworkSender.cs

示例14: Socket_SendToAsyncV4IPEndPointToV4Host_Throws

        public void Socket_SendToAsyncV4IPEndPointToV4Host_Throws()
        {
            Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp);
            socket.DualMode = false;

            SocketAsyncEventArgs args = new SocketAsyncEventArgs();
            args.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, UnusedPort);
            args.SetBuffer(new byte[1], 0, 1);

            bool async = socket.SendToAsync(args);
            Assert.False(async);
            Assert.Equal(SocketError.Fault, args.SocketError);
        }
开发者ID:rainersigwald,项目名称:corefx,代码行数:13,代码来源:DualModeSocketTest.cs

示例15: DualModeSendToAsync_IPEndPointToHost_Helper

        private void DualModeSendToAsync_IPEndPointToHost_Helper(IPAddress connectTo, IPAddress listenOn, bool dualModeServer)
        {
            int port;
            ManualResetEvent waitHandle = new ManualResetEvent(false);
            Socket client = new Socket(SocketType.Dgram, ProtocolType.Udp);
            using (SocketUdpServer server = new SocketUdpServer(listenOn, dualModeServer, out port))
            {
                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.RemoteEndPoint = new IPEndPoint(connectTo, port);
                args.SetBuffer(new byte[1], 0, 1);
                args.UserToken = waitHandle;
                args.Completed += AsyncCompleted;

                bool async = client.SendToAsync(args);
                if (async)
                {
                    Assert.True(waitHandle.WaitOne(5000), "Timeout while waiting for connection");
                }

                Assert.Equal(1, args.BytesTransferred);
                if (args.SocketError != SocketError.Success)
                {
                    throw new SocketException((int)args.SocketError);
                }

                bool success = server.WaitHandle.WaitOne(100); // Make sure the bytes were received
                if (!success)
                {
                    throw new TimeoutException();
                }
            }
        }
开发者ID:nnyamhon,项目名称:corefx,代码行数:32,代码来源:DualModeSocketTest.cs


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