Skip to content

Commit

Permalink
[feat] 新增IMqttHandler.Close,在网络连接关闭时触发,在IoT中可用于及时更新设备在线状态
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Oct 1, 2023
1 parent fbc6dea commit 7786c8d
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
10 changes: 10 additions & 0 deletions NewLife.MQTT/Handlers/IMqttHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ public interface IMqttHandler
/// <param name="message">消息</param>
/// <returns></returns>
Task<MqttIdMessage> PublishAsync(PublishMessage message);

/// <summary>关闭连接。网络连接被关闭时触发</summary>
/// <param name="reason"></param>
void Close(String reason);
}

/// <summary>MQTT处理器基类</summary>
Expand Down Expand Up @@ -250,6 +254,12 @@ protected virtual Packet Serialize(Object data)
}
#endregion

#region 辅助
/// <summary>关闭连接。网络连接被关闭时触发</summary>
/// <param name="reason"></param>
public virtual void Close(String reason) => Exchange?.Remove(Session.ID);
#endregion

#region 日志
/// <summary>链路追踪</summary>
public ITracer Tracer { get; set; }
Expand Down
8 changes: 7 additions & 1 deletion NewLife.MQTT/Handlers/MqttExchange.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,20 +47,26 @@ private void RemoveNotAlive(Object state)
var exp = DateTime.Now.Subtract(Expire);
var dic = new Dictionary<Int32, IMqttHandler>();
foreach (var item in _sessions)
{
if (item.Value is MqttHandler handler)
{
if (handler.Session == null)
dic.Add(item.Key, item.Value);
else if (handler.Session is not NetSession session || session.Disposed || session.Session == null)
dic.Add(item.Key, item.Value);
else if (session.Session.LastTime < exp)
dic.Add(item.Key, item.Value);
}
}

foreach (var item in dic)
{
_sessions.TryRemove(item.Key, out _);

// 销毁过期会话,促使断开连接
item.Value.TryDispose();
var handler = item.Value;
handler.Close(nameof(RemoveNotAlive));
handler.TryDispose();
}
}
#endregion
Expand Down
9 changes: 9 additions & 0 deletions NewLife.MQTT/MqttServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,15 @@ protected override void OnConnected()
base.OnConnected();
}

/// <summary>客户端连接已断开</summary>
/// <param name="reason"></param>
protected override void OnDisconnected(String reason)
{
Handler.Close(reason);

base.OnDisconnected(reason);
}

/// <summary>接收指令</summary>
/// <param name="e"></param>
protected override void OnReceive(ReceivedEventArgs e)
Expand Down

0 comments on commit 7786c8d

Please sign in to comment.