using Newtonsoft.Json.Linq;
using System;
using System.Threading.Tasks;
namespace Serein.Library.Network.WebSocketCommunication.Handle
{
///
/// 消息处理上下文
///
public class WebSocketMsgContext /*: IDisposable*/
{
public WebSocketMsgContext(Func sendAsync)
{
this._sendAsync = sendAsync;
}
public void Dispose()
{
JsonObject = null;
MsgTheme = null;
MsgId = null;
MsgData = null;
MsgData = null;
_sendAsync = null;
}
///
/// 标记是否已经处理,如果是,则提前退出
///
public bool Handle { get => _handle; set{
if(value)
{
Dispose();
_handle = value;
}
} }
public bool _handle = false;
///
/// 消息本体(JObject)
///
public JObject JsonObject { get; set; }
///
/// 此次消息请求的主题
///
public string MsgTheme { get; set; }
///
/// 此次消息附带的ID
///
public string MsgId { get; set; }
///
/// 此次消息的数据
///
public JObject MsgData { get; set; }
private Func _sendAsync;
///
/// 发送消息
///
///
///
public async Task SendAsync(string msg)
{
await _sendAsync.Invoke(msg);
}
///
/// 返回消息
///
///
///
///
///
public async Task RepliedAsync(WebSocketHandleModuleConfig moduleConfig,
WebSocketMsgContext context,
object data)
{
JObject jsonData;
if (data is null)
{
jsonData = new JObject()
{
[moduleConfig.MsgIdJsonKey] = context.MsgId,
[moduleConfig.ThemeJsonKey] = context.MsgTheme,
};
}
else
{
JToken dataToken;
if (data is System.Collections.IEnumerable || data is Array)
{
dataToken = JArray.FromObject(data);
}
else
{
dataToken = JObject.FromObject(data);
}
jsonData = new JObject()
{
[moduleConfig.MsgIdJsonKey] = context.MsgId,
[moduleConfig.ThemeJsonKey] = context.MsgTheme,
[moduleConfig.DataJsonKey] = dataToken
};
}
var msg = jsonData.ToString();
//Console.WriteLine($"[{msgId}] => {theme}");
await SendAsync(msg);
}
}
}