-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathDefaultTcpSocketClientProvider.cs
More file actions
92 lines (82 loc) · 2.48 KB
/
DefaultTcpSocketClientProvider.cs
File metadata and controls
92 lines (82 loc) · 2.48 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Copyright (c) BootstrapBlazor & Argo Zhang (argo@live.ca). All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Website: https://www.blazor.zone or https://argozhang.github.io/
using System.Net;
using System.Net.Sockets;
using System.Runtime.Versioning;
namespace BootstrapBlazor.TcpSocket;
/// <summary>
/// TcpSocket 客户端默认实现
/// </summary>
[UnsupportedOSPlatform("browser")]
class DefaultTcpSocketClientProvider : ITcpSocketClientProvider
{
private TcpClient? _client;
/// <summary>
/// <inheritdoc/>
/// </summary>
public bool IsConnected => _client?.Connected ?? false;
/// <summary>
/// <inheritdoc/>
/// </summary>
public IPEndPoint LocalEndPoint { get; set; } = new IPEndPoint(IPAddress.Any, 0);
/// <summary>
/// <inheritdoc/>
/// </summary>
public async ValueTask<bool> ConnectAsync(IPEndPoint endPoint, CancellationToken token = default)
{
_client = new TcpClient(LocalEndPoint);
await _client.ConnectAsync(endPoint, token).ConfigureAwait(false);
if (_client.Connected)
{
if (_client.Client.LocalEndPoint is IPEndPoint localEndPoint)
{
LocalEndPoint = localEndPoint;
}
}
return _client.Connected;
}
/// <summary>
/// <inheritdoc/>
/// </summary>
public async ValueTask<bool> SendAsync(ReadOnlyMemory<byte> data, CancellationToken token = default)
{
var ret = false;
if (_client != null)
{
var stream = _client.GetStream();
await stream.WriteAsync(data, token).ConfigureAwait(false);
ret = true;
}
return ret;
}
/// <summary>
/// <inheritdoc/>
/// </summary>
public async ValueTask<int> ReceiveAsync(Memory<byte> buffer, CancellationToken token = default)
{
var len = 0;
if (_client is { Connected: true })
{
var stream = _client.GetStream();
len = await stream.ReadAsync(buffer, token).ConfigureAwait(false);
if (len == 0)
{
_client.Close();
}
}
return len;
}
/// <summary>
/// <inheritdoc/>
/// </summary>
public ValueTask CloseAsync()
{
if (_client != null)
{
_client.Close();
_client = null;
}
return ValueTask.CompletedTask;
}
}