using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Serein.Library.Network.WebSocketCommunication.Handle { /// /// Json消息处理模块 /// public class WebSocketHandleModule { /// /// Json消息处理模块 /// public WebSocketHandleModule(string themeJsonKey, string dataJsonKey, string msgIdJsonKey) { this.ThemeJsonKey = themeJsonKey; this.DataJsonKey = dataJsonKey; this.MsgIdJsonKey = msgIdJsonKey; } /// /// 指示处理模块该使用 Json 中的哪个 Key 作为业务区别字段 /// public string ThemeJsonKey { get; } /// /// 指示处理模块该使用 Json 中的哪个 Key 作为业务数据字段 /// public string DataJsonKey { get; } /// /// 指示处理模块该使用 Json 中的哪个 Key 作为业务消息ID字段 /// public string MsgIdJsonKey { get; } /// /// 存储处理数据的配置 /// public ConcurrentDictionary MyHandleConfigs = new ConcurrentDictionary(); /// /// 添加处理配置 /// /// 处理模块 /// 处理配置 internal bool AddHandleConfigs(SocketHandleModule module,JsonMsgHandleConfig jsonMsgHandleConfig) { if (!MyHandleConfigs.ContainsKey(module.ThemeValue)) { MyHandleConfigs[module.ThemeValue] = jsonMsgHandleConfig; return true; } else { return false; } } /// /// 移除某个处理模块 /// /// /// public bool RemoveConfig(ISocketHandleModule socketControlBase) { foreach (var kv in MyHandleConfigs.ToArray()) { var config = kv.Value; if (config.HandleGuid.Equals(socketControlBase.HandleGuid)) { MyHandleConfigs.TryRemove(kv.Key, out _); } } return MyHandleConfigs.Count == 0; } /// /// 卸载当前模块的所有配置 /// public void UnloadConfig() { var temp = MyHandleConfigs.Values; MyHandleConfigs.Clear(); } /// /// 处理JSON数据 /// /// /// public void HandleSocketMsg(Func sendAsync, JObject jsonObject) { // 获取到消息 string theme = jsonObject.GetValue(ThemeJsonKey)?.ToString(); if (!MyHandleConfigs.TryGetValue(theme, out var handldConfig)) { // 没有主题 return; } string msgId = jsonObject.GetValue(MsgIdJsonKey)?.ToString(); try { JObject dataObj = jsonObject.GetValue(DataJsonKey)?.ToObject(); handldConfig.Handle(async (data) => { await this.SendAsync(sendAsync, msgId, theme, data); }, msgId, dataObj); } catch (Exception ex) { Console.WriteLine($"error in ws : {ex.Message}{Environment.NewLine}json value:{jsonObject}"); return; } } /// /// 发送消息 /// /// /// /// /// /// public async Task SendAsync(Func sendAsync,string msgId, string theme, object data) { JObject jsonData; if (data is null) { jsonData = new JObject() { [MsgIdJsonKey] = msgId, [ThemeJsonKey] = theme, }; } else { JToken dataToken; if ((data is System.Collections.IEnumerable || data is Array)) { dataToken = JArray.FromObject(data); } else { dataToken = JObject.FromObject(data); } jsonData = new JObject() { [MsgIdJsonKey] = msgId, [ThemeJsonKey] = theme, [DataJsonKey] = dataToken }; } var msg = jsonData.ToString(); //Console.WriteLine(msg); //Console.WriteLine(); await sendAsync.Invoke(msg); } } }