/// <summary> /// 开始监听 /// </summary> /// <param name="context"></param> /// <returns></returns> public static async Task Start(AspNetWebSocketContext context) { string socketID = context.QueryString[SOCKETIDNAME].ToString(); WebSocket socket = context.WebSocket; ContainsKeyInit(socket, socketID); ArraySegment <byte> buffer = new ArraySegment <byte>(new byte[2048]); #region 离线消息处理 if (MESSAGE_POOL.ContainsKey(socketID)) { List <SendMessageModel> msgs = MESSAGE_POOL[socketID]; foreach (SendMessageModel item in msgs) { buffer = new ArraySegment <byte>(Encoding.UTF8.GetBytes(ConvertManager.ModelToJson(item))); await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); } MESSAGE_POOL.Remove(socketID); } #endregion while (true) { if (socket.State == WebSocketState.Open) { WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None); string receivedMessage = Encoding.UTF8.GetString(buffer.Array, 0, result.Count); ReceivedMessageModel recM = ConvertManager.JsonToModel <ReceivedMessageModel>(receivedMessage); if (CONNECT_POOL.ContainsKey(recM.TargetSocketID)) //判断客户端是否在线 { WebSocket destSocket = CONNECT_POOL[recM.TargetSocketID]; //目的客户端 if (destSocket != null && destSocket.State == WebSocketState.Open) { buffer = new ArraySegment <byte>(Encoding.UTF8.GetBytes(ConvertManager.ModelToJson(new SendMessageModel(recM.Message)))); await destSocket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); } } else { await Task.Run(() => { if (!MESSAGE_POOL.ContainsKey(recM.TargetSocketID))//将用户添加至离线消息池中 { MESSAGE_POOL.Add(recM.TargetSocketID, new List <SendMessageModel>()); } MESSAGE_POOL[recM.TargetSocketID].Add(new SendMessageModel(recM.Message));//添加离线消息 }); } } else { if (CONNECT_POOL.ContainsKey(socketID)) { CONNECT_POOL.Remove(socketID); } break; } } }
public WeChatManagerTests() { #region 测试代码--微信Token string resStr = "{\"access_token\":\"zWtGZHO2EHfig-nBhIUb0XtQrh88kqDXV4RalOUvZi22tFELCKieW30O85aQafsH8DOKX1HS-J1Scb7Bdi7jShgrLg4Jc8_sBxcFuqYnGyf5QplcIZLXwOt7tHlcxDKEJPFaAIAXDT\",\"expires_in\":7200}"; WeChatTokenModel tempTokenM = ConvertManager.JsonToModel <WeChatTokenModel>(resStr); WebCacheManager.Set("MATERALWECHATTOKENKEY", tempTokenM, DateTimeOffset.Now.AddSeconds(tempTokenM.expires_in - 60)); #endregion }