Skip to content

Commit

Permalink
[feat] 网络库增加OpenAsync/CloseAsync
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Dec 11, 2024
1 parent 4141bdb commit e682eab
Show file tree
Hide file tree
Showing 5 changed files with 64 additions and 29 deletions.
11 changes: 11 additions & 0 deletions NewLife.Core/Net/ISocketClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,22 @@ public interface ISocketClient : ISocketRemote
/// <returns>是否成功</returns>
Boolean Open();

/// <summary>打开连接</summary>
/// <param name="cancellationToken">取消通知</param>
/// <returns>是否成功</returns>
Task<Boolean> OpenAsync(CancellationToken cancellationToken);

/// <summary>关闭连接</summary>
/// <param name="reason">关闭原因。便于日志分析</param>
/// <returns>是否成功</returns>
Boolean Close(String reason);

/// <summary>关闭连接</summary>
/// <param name="reason">关闭原因。便于日志分析</param>
/// <param name="cancellationToken">取消通知</param>
/// <returns>是否成功</returns>
Task<Boolean> CloseAsync(String reason, CancellationToken cancellationToken);

/// <summary>打开后触发。</summary>
event EventHandler Opened;

Expand Down
36 changes: 25 additions & 11 deletions NewLife.Core/Net/SessionBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,21 +97,27 @@ protected override void Dispose(Boolean disposing)

/// <summary>打开</summary>
/// <returns>是否成功</returns>
public virtual Boolean Open()
public virtual Boolean Open() => OpenAsync().ConfigureAwait(false).GetAwaiter().GetResult();

/// <summary>打开</summary>
/// <param name="cancellationToken">取消通知</param>
/// <returns>是否成功</returns>
public virtual async Task<Boolean> OpenAsync(CancellationToken cancellationToken = default)
{
if (Disposed) throw new ObjectDisposedException(GetType().Name);

if (Active) return true;
lock (this)
if (!Monitor.TryEnter(this, Timeout + 100)) return false;
{
if (Active) return true;
if (cancellationToken.IsCancellationRequested) return false;

using var span = Tracer?.NewSpan($"net:{Name}:Open", Remote?.ToString());
try
{
_RecvCount = 0;

var rs = OnOpen();
var rs = await OnOpenAsync(cancellationToken).ConfigureAwait(false);
if (!rs) return false;

var timeout = Timeout;
Expand Down Expand Up @@ -151,19 +157,27 @@ public virtual Boolean Open()
}

/// <summary>打开</summary>
/// <param name="cancellationToken">取消通知</param>
/// <returns></returns>
[MemberNotNullWhen(true, nameof(Client))]
protected abstract Boolean OnOpen();
protected abstract Task<Boolean> OnOpenAsync(CancellationToken cancellationToken);

/// <summary>关闭</summary>
/// <param name="reason">关闭原因。便于日志分析</param>
/// <returns>是否成功</returns>
public virtual Boolean Close(String reason)
public virtual Boolean Close(String reason) => CloseAsync(reason).ConfigureAwait(false).GetAwaiter().GetResult();

/// <summary>关闭</summary>
/// <param name="reason">关闭原因。便于日志分析</param>
/// <param name="cancellationToken">取消通知</param>
/// <returns>是否成功</returns>
public virtual async Task<Boolean> CloseAsync(String reason, CancellationToken cancellationToken = default)
{
if (!Active) return true;
lock (this)
if (!Monitor.TryEnter(this, Timeout + 100)) return false;
{
if (!Active) return true;
if (cancellationToken.IsCancellationRequested) return false;

using var span = Tracer?.NewSpan($"net:{Name}:Close", Remote?.ToString());
try
Expand All @@ -173,17 +187,16 @@ public virtual Boolean Close(String reason)
// 管道
Pipeline?.Close(CreateContext(this), reason);

var rs = true;
if (OnClose(reason ?? (GetType().Name + "Close"))) rs = false;
var rs = await OnCloseAsync(reason ?? (GetType().Name + "Close"), cancellationToken).ConfigureAwait(false);

_RecvCount = 0;

// 触发关闭完成的事件
Closed?.Invoke(this, EventArgs.Empty);

Active = rs;
Active = !rs;

return !rs;
return rs;
}
catch (Exception ex)
{
Expand All @@ -195,8 +208,9 @@ public virtual Boolean Close(String reason)

/// <summary>关闭</summary>
/// <param name="reason">关闭原因。便于日志分析</param>
/// <param name="cancellationToken">取消通知</param>
/// <returns></returns>
protected abstract Boolean OnClose(String reason);
protected abstract Task<Boolean> OnCloseAsync(String reason, CancellationToken cancellationToken);

Boolean ITransport.Close() => Close("TransportClose");

Expand Down
20 changes: 12 additions & 8 deletions NewLife.Core/Net/TcpSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,8 @@ internal void Start()
}

/// <summary>打开</summary>
protected override Boolean OnOpen()
/// <param name="cancellationToken">取消通知</param>
protected override async Task<Boolean> OnOpenAsync(CancellationToken cancellationToken)
{
// 服务端会话没有打开
if (_Server != null) return false;
Expand Down Expand Up @@ -173,8 +174,9 @@ protected override Boolean OnOpen()
{
#if NET5_0_OR_GREATER
var cts = new CancellationTokenSource(timeout);
using var _ = cts.Token.Register(() => sock.Close());
sock.ConnectAsync(addrs, uri.Port, cts.Token).AsTask().Wait(timeout);
var cts2 = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cts.Token);
using var _ = cts2.Token.Register(() => sock.Close());
await sock.ConnectAsync(addrs, uri.Port, cts2.Token).ConfigureAwait(false);
#else
// 采用异步来解决连接超时设置问题
var ar = sock.BeginConnect(addrs, uri.Port, null, null);
Expand All @@ -184,7 +186,8 @@ protected override Boolean OnOpen()
throw new TimeoutException($"The connection to server [{uri}] timed out! [{timeout}ms]");
}

sock.EndConnect(ar);
//sock.EndConnect(ar);
await Task.Factory.FromAsync(ar, sock.EndConnect).ConfigureAwait(false);
#endif
}

Expand All @@ -208,7 +211,7 @@ protected override Boolean OnOpen()

var ns = new NetworkStream(sock);
var sslStream = new SslStream(ns, false, OnCertificateValidationCallback);
sslStream.AuthenticateAsClient(host, certs, sp, false);
await sslStream.AuthenticateAsClientAsync(host, certs, sp, false).ConfigureAwait(false);

_Stream = sslStream;
}
Expand Down Expand Up @@ -251,7 +254,8 @@ private Boolean OnCertificateValidationCallback(Object? sender, X509Certificate?

/// <summary>关闭</summary>
/// <param name="reason">关闭原因。便于日志分析</param>
protected override Boolean OnClose(String reason)
/// <param name="cancellationToken">取消通知</param>
protected override Task<Boolean> OnCloseAsync(String reason, CancellationToken cancellationToken)
{
var client = Client;
if (client != null)
Expand All @@ -275,12 +279,12 @@ protected override Boolean OnClose(String reason)
if (!ex.IsDisposed()) OnError("Close", ex);
//if (ThrowException) throw;

return false;
return Task.FromResult(false);
}
Client = null;
}

return true;
return Task.FromResult(true);
}

#endregion 方法
Expand Down
13 changes: 8 additions & 5 deletions NewLife.Core/Net/UdpServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ protected override void Dispose(Boolean disposing)

#region 方法
/// <summary>打开</summary>
protected override Boolean OnOpen()
/// <param name="cancellationToken">取消通知</param>
protected override Task<Boolean> OnOpenAsync(CancellationToken cancellationToken)
{
var sock = Client;
if (sock == null || !sock.IsBound)
Expand Down Expand Up @@ -101,11 +102,13 @@ protected override Boolean OnOpen()
WriteLog("Open {0}", this);
}

return true;
return Task.FromResult(true);
}

/// <summary>关闭</summary>
protected override Boolean OnClose(String reason)
/// <param name="reason">关闭原因。便于日志分析</param>
/// <param name="cancellationToken">取消通知</param>
protected override Task<Boolean> OnCloseAsync(String reason, CancellationToken cancellationToken)
{
var sock = Client;
if (sock != null)
Expand All @@ -132,11 +135,11 @@ protected override Boolean OnClose(String reason)
if (!ex.IsDisposed()) OnError("Close", ex);
//if (ThrowException) throw;

return false;
return Task.FromResult(false);
}
}

return true;
return Task.FromResult(true);
}
#endregion

Expand Down
13 changes: 8 additions & 5 deletions NewLife.Core/Net/WebSocketClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,18 @@ public WebSocketClient(String url) : this(new Uri(url)) { }
#endregion

/// <summary>打开连接,建立WebSocket请求</summary>
/// <param name="cancellationToken">取消通知</param>
/// <returns></returns>
protected override Boolean OnOpen()
protected override async Task<Boolean> OnOpenAsync(CancellationToken cancellationToken)
{
var remote = Remote;
if (remote == null || remote.Address.IsAny() || remote.Port == 0)
{
remote = Remote = new NetUri(Uri.ToString());
}

if (!base.OnOpen()) return false;
var rs = await base.OnOpenAsync(cancellationToken).ConfigureAwait(false);
if (!rs) return false;

//// 连接必须是ws/wss协议
//if (remote.Type != NetType.WebSocket) return false;
Expand All @@ -79,14 +81,15 @@ protected override Boolean OnOpen()
}

/// <summary>关闭连接</summary>
/// <param name="reason"></param>
/// <param name="reason">关闭原因。便于日志分析</param>
/// <param name="cancellationToken">取消通知</param>
/// <returns></returns>
protected override Boolean OnClose(String reason)
protected override Task<Boolean> OnCloseAsync(String reason, CancellationToken cancellationToken)
{
_timer.TryDispose();
_timer = null;

return base.OnClose(reason);
return base.OnCloseAsync(reason, cancellationToken);
}

/// <summary>设置请求头。ws握手时可以传递Token</summary>
Expand Down

0 comments on commit e682eab

Please sign in to comment.