本文整理汇总了C#中TcpListener.AcceptSocketAsync方法的典型用法代码示例。如果您正苦于以下问题:C# TcpListener.AcceptSocketAsync方法的具体用法?C# TcpListener.AcceptSocketAsync怎么用?C# TcpListener.AcceptSocketAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类TcpListener
的用法示例。
在下文中一共展示了TcpListener.AcceptSocketAsync方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SendRecvPollSync_TcpListener_Socket
public void SendRecvPollSync_TcpListener_Socket(IPAddress listenAt, bool pollBeforeOperation)
{
const int BytesToSend = 123456;
const int ListenBacklog = 1;
const int TestTimeout = 30000;
var listener = new TcpListener(listenAt, 0);
listener.Start(ListenBacklog);
try
{
int bytesReceived = 0;
var receivedChecksum = new Fletcher32();
Task serverTask = Task.Run(async () =>
{
using (Socket remote = await listener.AcceptSocketAsync())
{
var recvBuffer = new byte[256];
while (true)
{
if (pollBeforeOperation)
{
Assert.True(remote.Poll(-1, SelectMode.SelectRead), "Read poll before completion should have succeeded");
}
int received = remote.Receive(recvBuffer, 0, recvBuffer.Length, SocketFlags.None);
if (received == 0)
{
Assert.True(remote.Poll(0, SelectMode.SelectRead), "Read poll after completion should have succeeded");
break;
}
bytesReceived += received;
receivedChecksum.Add(recvBuffer, 0, received);
}
}
});
int bytesSent = 0;
var sentChecksum = new Fletcher32();
Task clientTask = Task.Run(async () =>
{
var clientEndpoint = (IPEndPoint)listener.LocalEndpoint;
using (var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
await client.ConnectAsync(clientEndpoint.Address, clientEndpoint.Port);
if (pollBeforeOperation)
{
Assert.False(client.Poll(TestTimeout, SelectMode.SelectRead), "Expected writer's read poll to fail after timeout");
}
var random = new Random();
var sendBuffer = new byte[512];
for (int remaining = BytesToSend, sent = 0; remaining > 0; remaining -= sent)
{
random.NextBytes(sendBuffer);
if (pollBeforeOperation)
{
Assert.True(client.Poll(-1, SelectMode.SelectWrite), "Write poll should have succeeded");
}
sent = client.Send(sendBuffer, 0, Math.Min(sendBuffer.Length, remaining), SocketFlags.None);
bytesSent += sent;
sentChecksum.Add(sendBuffer, 0, sent);
}
}
});
Assert.True(Task.WaitAll(new[] { serverTask, clientTask }, TestTimeout), "Wait timed out");
Assert.Equal(bytesSent, bytesReceived);
Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum);
}
finally
{
listener.Stop();
}
}