本文整理汇总了C#中TcpListener.AcceptTcpClientAsync方法的典型用法代码示例。如果您正苦于以下问题:C# TcpListener.AcceptTcpClientAsync方法的具体用法?C# TcpListener.AcceptTcpClientAsync怎么用?C# TcpListener.AcceptTcpClientAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类TcpListener
的用法示例。
在下文中一共展示了TcpListener.AcceptTcpClientAsync方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: RunWithConnectedNetworkStreamsAsync
/// <summary>
/// Creates a pair of connected NetworkStreams and invokes the provided <paramref name="func"/>
/// with them as arguments.
/// </summary>
private static async Task RunWithConnectedNetworkStreamsAsync(Func<NetworkStream, NetworkStream, Task> func)
{
var listener = new TcpListener(IPAddress.Loopback, 0);
try
{
listener.Start(1);
var clientEndpoint = (IPEndPoint)listener.LocalEndpoint;
using (var client = new TcpClient(clientEndpoint.AddressFamily))
{
Task<TcpClient> remoteTask = listener.AcceptTcpClientAsync();
Task clientConnectTask = client.ConnectAsync(clientEndpoint.Address, clientEndpoint.Port);
await Task.WhenAll(remoteTask, clientConnectTask);
using (TcpClient remote = remoteTask.Result)
using (NetworkStream serverStream = remote.GetStream())
using (NetworkStream clientStream = client.GetStream())
{
await func(serverStream, clientStream);
}
}
}
finally
{
listener.Stop();
}
}
示例2: SendRecvAsync_TcpListener_TcpClient
public void SendRecvAsync_TcpListener_TcpClient(IPAddress listenAt)
{
const int BytesToSend = 123456;
const int ListenBacklog = 1;
const int LingerTime = 10;
const int TestTimeout = 30000;
var listener = new TcpListener(listenAt, 0);
listener.Start(ListenBacklog);
int bytesReceived = 0;
var receivedChecksum = new Fletcher32();
Task serverTask = Task.Run(async () =>
{
using (TcpClient remote = await listener.AcceptTcpClientAsync())
using (NetworkStream stream = remote.GetStream())
{
var recvBuffer = new byte[256];
for (;;)
{
int received = await stream.ReadAsync(recvBuffer, 0, recvBuffer.Length);
if (received == 0)
{
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 TcpClient(clientEndpoint.AddressFamily))
{
await client.ConnectAsync(clientEndpoint.Address, clientEndpoint.Port);
using (NetworkStream stream = client.GetStream())
{
var random = new Random();
var sendBuffer = new byte[512];
for (int remaining = BytesToSend, sent = 0; remaining > 0; remaining -= sent)
{
random.NextBytes(sendBuffer);
sent = Math.Min(sendBuffer.Length, remaining);
await stream.WriteAsync(sendBuffer, 0, sent);
bytesSent += sent;
sentChecksum.Add(sendBuffer, 0, sent);
}
client.LingerState = new LingerOption(true, LingerTime);
}
}
});
Assert.True(Task.WaitAll(new[] { serverTask, clientTask }, TestTimeout));
Assert.Equal(bytesSent, bytesReceived);
Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum);
}