-
-
Notifications
You must be signed in to change notification settings - Fork 979
Expand file tree
/
Copy pathSocketAbstraction.Async.cs
More file actions
50 lines (44 loc) · 1.72 KB
/
SocketAbstraction.Async.cs
File metadata and controls
50 lines (44 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#if NET6_0_OR_GREATER
using System;
using System.Diagnostics;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace Renci.SshNet.Abstractions
{
internal static partial class SocketAbstraction
{
public static ValueTask<int> ReadAsync(Socket socket, byte[] buffer, CancellationToken cancellationToken)
{
return socket.ReceiveAsync(buffer, SocketFlags.None, cancellationToken);
}
public static ValueTask SendAsync(Socket socket, ReadOnlyMemory<byte> data, CancellationToken cancellationToken = default)
{
Debug.Assert(socket != null);
Debug.Assert(data.Length > 0);
if (cancellationToken.IsCancellationRequested)
{
return ValueTask.FromCanceled(cancellationToken);
}
return SendAsyncCore(socket, data, cancellationToken);
static async ValueTask SendAsyncCore(Socket socket, ReadOnlyMemory<byte> data, CancellationToken cancellationToken)
{
do
{
try
{
var bytesSent = await socket.SendAsync(data, SocketFlags.None, cancellationToken).ConfigureAwait(false);
data = data.Slice(bytesSent);
}
catch (SocketException ex) when (IsErrorResumable(ex.SocketErrorCode))
{
// Buffer may be full; attempt a short delay and retry
await Task.Delay(30, cancellationToken).ConfigureAwait(false);
}
}
while (data.Length > 0);
}
}
}
}
#endif // NET6_0_OR_GREATER