Skip to content

Commit

Permalink
WebSocket客户端服务端增加心跳PingPong支持,默认120秒
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Apr 27, 2024
1 parent 0c4d187 commit 6b0a434
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 2 deletions.
7 changes: 6 additions & 1 deletion NewLife.Core/Data/Packet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -493,13 +493,18 @@ public String ToBase64()
/// <summary>重载类型转换,字节数组直接转为Packet对象</summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator Packet(Byte[] value) => value == null ? null! : new Packet(value);
public static implicit operator Packet(Byte[] value) => value == null ? null! : new(value);

/// <summary>重载类型转换,一维数组直接转为Packet对象</summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator Packet(ArraySegment<Byte> value) => new(value);

/// <summary>重载类型转换,字符串直接转为Packet对象</summary>
/// <param name="value"></param>
/// <returns></returns>
public static implicit operator Packet(String value) => new(value.GetBytes());

/// <summary>已重载</summary>
/// <returns></returns>
public override String ToString() => $"[{Data.Length}]({Offset}, {Count})" + (Next == null ? "" : $"<{Total}>");
Expand Down
6 changes: 5 additions & 1 deletion NewLife.Core/Http/WebSocket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,11 @@ public void Process(Packet pk)
break;
case WebSocketMessageType.Ping:
{
var msg = new WebSocketMessage { Type = WebSocketMessageType.Pong, MaskKey = Rand.NextBytes(4) };
var msg = new WebSocketMessage
{
Type = WebSocketMessageType.Pong,
Payload = $"Pong {DateTime.UtcNow.ToFullString()}",
};
session.Send(msg.ToPacket());
}
break;
Expand Down
36 changes: 36 additions & 0 deletions NewLife.Core/Net/WebSocketClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using NewLife.Log;
using NewLife.Net.Handlers;
using NewLife.Security;
using NewLife.Threading;
#if !NET45
using TaskEx = System.Threading.Tasks.Task;
#endif
Expand All @@ -17,6 +18,9 @@ public class WebSocketClient : TcpSession
#region 属性
/// <summary>资源地址</summary>
public Uri Uri { get; set; } = null!;

/// <summary>WebSocket心跳间隔。默认60秒</summary>
public TimeSpan KeepAlive { get; set; } = TimeSpan.FromSeconds(120);
#endregion

#region 构造
Expand Down Expand Up @@ -63,9 +67,24 @@ protected override Boolean OnOpen()

//Active = false;

var p = (Int32)KeepAlive.TotalMilliseconds;
if (p > 0)
_timer = new TimerX(DoPing, null, 5_000, p) { Async = true };

return true;
}

/// <summary>关闭连接</summary>
/// <param name="reason"></param>
/// <returns></returns>
protected override Boolean OnClose(String reason)
{
_timer.TryDispose();
_timer = null;

return base.OnClose(reason);
}

#region 消息收发
/// <summary>接收WebSocket消息</summary>
/// <param name="cancellationToken"></param>
Expand Down Expand Up @@ -148,6 +167,23 @@ public Task CloseAsync(Int32 closeStatus, String? statusDescription = null, Canc
}
#endregion

#region 心跳
private TimerX? _timer;
private void DoPing(Object? state)
{
var msg = new WebSocketMessage
{
Type = WebSocketMessageType.Ping,
Payload = $"Ping {DateTime.UtcNow.ToFullString()}",
};

SendMessage(msg);

var p = (Int32)KeepAlive.TotalMilliseconds;
if (_timer != null) _timer.Period = p;
}
#endregion

#region 辅助
/// <summary>握手</summary>
/// <param name="client"></param>
Expand Down
2 changes: 2 additions & 0 deletions Samples/Zero.HttpServer/ClientTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ public static async Task WebSocketClientTest()
var rs = await client.ReceiveMessageAsync(default);
client.WriteLog(rs.Payload.ToStr());

await Task.Delay(6_000);

// 关闭连接
await client.CloseAsync(1000, "通信完成", default);
client.WriteLog("Close");
Expand Down

0 comments on commit 6b0a434

Please sign in to comment.