Browse Source

TcpClient,去除 Connected 属性(不可靠),增加 Online 属性用于判断在线状态。

master
王厅 1 week ago
parent
commit
ba717f4d3d
  1. 18
      Apewer/Network/Extensions.cs
  2. 9
      Apewer/Network/TcpClient.cs

18
Apewer/Network/Extension.cs → Apewer/Network/Extensions.cs

@ -9,7 +9,7 @@ namespace Apewer.Network
{
/// <summary>扩展方法。</summary>
public static class Extension
public static class Extensions
{
/// <summary>添加邮件账户。</summary>
@ -155,15 +155,31 @@ namespace Apewer.Network
return json;
}
/// <summary>检查 Socket 在线状态。</summary>
/// <exception cref="NotSupportedException"></exception>
/// <exception cref="ObjectDisposedException"></exception>
/// <exception cref="SocketException"></exception>
public static bool Online(this Socket socket)
{
if (socket == null) return false;
var pending = socket.Poll(1000, System.Net.Sockets.SelectMode.SelectRead);
var available = socket.Available;
var offline = pending && available == 0;
return !offline;
}
/// <summary>从套接字接收数据。</summary>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentOutOfRangeException"></exception>
/// <exception cref="InvalidOperationException"></exception>
/// <exception cref="SocketException"></exception>
/// <exception cref="ObjectDisposedException"></exception>
/// <exception cref="System.Security.SecurityException"></exception>
public static byte[] Receive(this Socket socket, int maxLength = 1024)
{
if (socket == null) throw new ArgumentNullException(nameof(socket));
if (maxLength < 0 || maxLength > 65535) throw new ArgumentOutOfRangeException(nameof(maxLength));
var buffer = new byte[maxLength];
var received = socket.Receive(buffer, 0, maxLength, SocketFlags.None);

9
Apewer/Network/TcpClient.cs

@ -14,15 +14,15 @@ namespace Apewer.Network
/// <summary>套接字实例。</summary>
public Socket Socket { get => _socket; }
/// <summary>在线。</summary>
public bool Online { get => Extensions.Online(_socket); }
/// <summary>本地终结点。</summary>
public IPEndPoint LocalEndPoint { get; private set; }
/// <summary>远程终结点。</summary>
public IPEndPoint RemoteEndPoint { get; private set; }
/// <summary>已连接。</summary>
public bool Connected { get => _socket != null && _socket.Connected; }
/// <summary>启动客户端,并连接到服务端。</summary>
public TcpClient(string ip, int port) : this(IPAddress.Parse(ip), port) { }
@ -49,9 +49,6 @@ namespace Apewer.Network
#endif
}
/// <summary>在线。</summary>
public bool Online { get => Extensions.Online(_socket); }
/// <summary>接收。</summary>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentOutOfRangeException"></exception>

Loading…
Cancel
Save