Esempio n. 1
0
        private void Connection()
        {
            try
            {
                syn = SynchronizationContext.Current;

                if (client == null)
                {
                    // 实例化 Socket
                    client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    client.ReceiveBufferSize = ConstHelper.BUFFER_SIZE;
                    client.SendBufferSize    = ConstHelper.BUFFER_SIZE;
                    client.NoDelay           = true;
                }

                // 实例化 SocketAsyncEventArgs ,用于对 Socket 做异步操作,很方便
                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                // 服务器的 EndPoint
                args.RemoteEndPoint = new DnsEndPoint(HttpContext.Current.Request.UserHostAddress, 4518);
                // 异步操作完成后执行的事件
                args.Completed += new EventHandler <SocketAsyncEventArgs>(OnSocketConnectCompleted);

                // 异步连接服务端
                client.ConnectAsync(args);
            }
            catch (Exception ex)
            {
                LogCommonHelper.WriteLog("Connection:" + ex.InnerException.Message);
            }
        }
Esempio n. 2
0
        private static void OperationSocketData(int receiveLength, SocketP2PEntity client)
        {
            try
            {
                SendToClientCompleteHandler sendToClientCompleteHandler = new SendToClientCompleteHandler(SendToClientComplete);
                OutPutSystemMessageHandler  outPutSystemMessageHandler  = new OutPutSystemMessageHandler(OutPutSystemMessage);

                string json = Encoding.UTF8.GetString(client.Buffer, 0, receiveLength);

                if (string.IsNullOrEmpty(json))
                {
                    LogCommonHelper.WriteLog("p2p服务接收到数据:Null");
                }
                else
                {
                    LogCommonHelper.WriteLog("p2p服务接收到数据:" + json);

                    SocketP2PMessageEntity message = JsonHelper.Deserialize <SocketP2PMessageEntity>(json);

                    ManagerIdentity.Execute(client, message, Clients, Queue, sendToClientCompleteHandler, outPutSystemMessageHandler);
                }
            }
            catch (Exception ex)
            {
                LogCommonHelper.WriteLog("OperationSocketData:" + ex.InnerException.Message);
            }
        }
Esempio n. 3
0
        /// <summary>
        /// 连接完成回调处理
        /// </summary>
        private void OnSocketConnectCompleted(object sender, SocketAsyncEventArgs e)
        {
            try
            {
                //显示连接结果
                if (client == null || !client.Connected)
                {
                    LogCommonHelper.WriteLog("Ws 无法连接到服务器,请刷新后再试...");
                }
                else
                {
                    LogCommonHelper.WriteLog("Ws 与服务器连接成功...");

                    SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                    args.RemoteEndPoint = e.RemoteEndPoint;

                    // 设置数据缓冲区
                    byte[] buffer = new byte[ConstHelper.BUFFER_SIZE];
                    args.SetBuffer(buffer, 0, buffer.Length);

                    args.Completed += new EventHandler <SocketAsyncEventArgs>(OnSocketReceiveCompleted);
                    // 异步地从服务端 Socket 接收数据
                    client.ReceiveAsync(args);

                    // 请求客服
                    this.Send(message);
                }
            }
            catch (Exception ex)
            {
                LogCommonHelper.WriteLog("Ws OnSocketConnectCompleted:" + ex.InnerException.Message);
            }
        }
Esempio n. 4
0
        protected override void ValidateIdentity(SocketP2PEntity client, SocketP2PMessageEntity message,
                                                 List <SocketP2PEntity> clients, List <SocketP2PEntity> queue,
                                                 SendToClientCompleteHandler sendToClientCompleteHandler, OutPutSystemMessageHandler outPutSystemMessageHandler)
        {
            try
            {
                LogCommonHelper.WriteLog("我是客服,等待访客请求");

                var PreparingMessageEntity = NewP2PMessage();
                PreparingMessageEntity.Sender   = null;
                PreparingMessageEntity.Receiver = client.Sender;
                PreparingMessageEntity.Identity = "SERVER";
                PreparingMessageEntity.Data     = string.Format("您好,客服({0}),请您等待访客请求...", client.Sender);
                PreparingMessageEntity.Owner    = client.Owner;
                PreparingMessageEntity.WeiXinNo = client.WeiXinNo;
                PreparingMessageEntity.OpenId   = client.OpenId;

                SendMessageToTerminal(PreparingMessageEntity, client, sendToClientCompleteHandler);
            }
            catch (SocketException ex)
            {
                client.Socket.Close();
                clients.Remove(client);
                outPutSystemMessageHandler(ex.Message);
            }
        }
Esempio n. 5
0
        public void ResponseMsg(string postStr, HttpContext context)
        {
            try
            {
                if (string.IsNullOrEmpty(postStr))
                {
                    LogCommonHelper.WriteLog("接收到空值");
                    context.Response.Write(string.Empty);
                    context.Response.End();
                }
                else
                {
                    var signature = context.Request.QueryString.Get("signature");
                    LogCommonHelper.WriteLog("signature:" + signature);

                    var timestamp = context.Request.QueryString.Get("timestamp");
                    LogCommonHelper.WriteLog("timestamp:" + timestamp);

                    var nonce = context.Request.QueryString.Get("nonce");
                    LogCommonHelper.WriteLog("nonce:" + nonce);

                    string result = MessageProvider.Save(postStr, signature, timestamp, nonce);
                    LogCommonHelper.WriteLog(result);
                    context.Response.Write(result);
                    context.Response.End();
                }
            }
            catch (Exception ex)
            {
                LogCommonHelper.WriteLog(ex.Message);
            }
        }
Esempio n. 6
0
        private void Send(SocketP2PMessageEntity message)
        {
            if (client != null && client.Connected)
            {
                try
                {
                    LogCommonHelper.WriteLog("Ws 开始发送到服务器的数据");

                    byte[] buffer = this.MessageToBytes(message);

                    List <ArraySegment <byte> > _lst = new List <ArraySegment <byte> >();
                    _lst.Add(new ArraySegment <byte>(buffer));
                    SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                    args.RemoteEndPoint = client.RemoteEndPoint;
                    args.Completed     += new EventHandler <SocketAsyncEventArgs>(SendArgs_Completed);
                    args.BufferList     = _lst;
                    client.SendAsync(args);

                    Thread.Sleep(500);
                }
                catch (Exception ex)
                {
                    LogCommonHelper.WriteLog("Ws Sending Message:" + ex.InnerException.Message);
                }
            }
            else
            {
                LogCommonHelper.WriteLog("Ws 已与服务器断开链接...");
            }
        }
Esempio n. 7
0
        public static string Save(string postStr, string signature, string timestamp, string nonce)
        {
            ManagerMessage manager = ManagerMessage.CreateInstance();
            string         key     = KeyBuilder.GetKey(postStr);

            LogCommonHelper.WriteLog("Key:" + key);
            return(manager.Save(key, postStr, signature, timestamp, nonce));
        }
Esempio n. 8
0
        public string Operation(NameValueCollection parameters)
        {
            try
            {
                if (ConfigurationHelper.IsLog)
                {
                    foreach (var item in parameters.AllKeys)
                    {
                        LogCommonHelper.WriteLog(string.Format("参数{0} / 值{1}", item, parameters[item]));
                    }
                }

                string[] names = GetNamesOfMustParamter();

                foreach (var item in names)
                {
                    if (parameters[item] == null)
                    {
                        return(string.Format(ConstHelper.ERROR_100003, item));
                    }
                }


                dynamic token = GetAccessToken(parameters);
                if (token is AccessTokenEntity)
                {
                    AccessTokenEntity entity = token as AccessTokenEntity;
                    string            data   = Working(entity.access_token, parameters);
                    try
                    {
                        var model = JsonHelper.Deserialize <ErrorEntity>(data);
                        return(JsonHelper.Serialize(GetErrorChineseMessage(model)));
                    }
                    catch
                    {
                        return(data);
                    }
                }
                else if (token is ErrorEntity)
                {
                    return(JsonHelper.Serialize(GetErrorChineseMessage(token as ErrorEntity)));
                }
                else if (token is string)
                {
                    return(token);
                }
                else
                {
                    LogCommonHelper.WriteLog("Error:" + ConstHelper.ERROR_999998);
                    return(ConstHelper.ERROR_999998);
                }
            }
            catch (Exception ex)
            {
                return(string.Format(ConstHelper.ERROR_999999, ex.InnerException.Message));
            }
        }
Esempio n. 9
0
        protected virtual void SendMessageToTerminal(SocketP2PMessageEntity message, SocketP2PEntity client,
                                                     SendToClientCompleteHandler sendToClientCompleteHandler)
        {
            try
            {
                if (!string.IsNullOrEmpty(client.OpenId))
                {
                    LogCommonHelper.WriteLog("Identity : " + message.Identity);

                    string data = message.Data;
                    if (Equals(message.Identity, "CUSTOMER"))
                    {
                        data = string.Format("访客({0}) {1} : {2}", message.Sender, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), message.Data);
                    }

                    string msg = "{\"touser\":\"" + client.OpenId + "\",\"msgtype\":\"text\", \"text\":{\"content\":\"" + data + "\"}}";
                    LogCommonHelper.WriteLog("msg:" + msg);

                    if (!string.IsNullOrEmpty(msg))
                    {
                        WxAccountService.WxAccountServiceSoapClient WxAccount       = new WxAccountService.WxAccountServiceSoapClient();
                        WxAccountService.WxAccountEntity            WxAccountEntity = WxAccount.GetByWeiXinNo(message.WeiXinNo);
                        if (WxAccountEntity == null)
                        {
                            LogCommonHelper.WriteLog("WxAccount为NULL"); return;
                        }

                        LogCommonHelper.WriteLog("已经获取WxAccount信息");
                        LogCommonHelper.WriteLog("UserName : "******"Token : " + WxAccountEntity.Token);
                        LogCommonHelper.WriteLog("AppId : " + WxAccountEntity.AppId);
                        LogCommonHelper.WriteLog("Secret : " + WxAccountEntity.Secret);

                        string un    = WxAccountEntity.UserName;
                        string unkey = CryptHelper.MD5(string.Format("{0}{1}", un, WxAccountEntity.Token));
                        string url   = string.Format("{0}?key=C011&un={1}&unkey={2}", ConfigurationHelper.Get("WxUrl"), un, unkey);
                        LogCommonHelper.WriteLog("URL:" + url);
                        string strReply = WebHelper.GetFormWebRequest(url, "POST", "body=" + msg);
                    }
                }
                else
                {
                    string json = JsonHelper.Serialize(message);
                    LogCommonHelper.WriteLog("发送Socket消息,内容:" + json);
                    byte[] buffer = Encoding.UTF8.GetBytes(json);
                    client.Socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(sendToClientCompleteHandler), client);
                }
            }
            catch (Exception ex)
            {
                LogCommonHelper.WriteLog("SendMessageToTerminal Exception:" + ex.InnerException.Message);
            }
        }
Esempio n. 10
0
        private void Sending(TEntity entity, SocketP2PEntity client, SocketP2PMessageEntity message,
                             List <SocketP2PEntity> clients, List <SocketP2PEntity> queue,
                             SendToClientCompleteHandler sendToClientCompleteHandler, OutPutSystemMessageHandler outPutSystemMessageHandler)
        {
            if (message.Identity == "SERVER")
            {
                LogCommonHelper.WriteLog(string.Format("由系统发给{0}({1})的消息",
                                                       message.Receiver.Length == 10 ? "访客" : "客服",
                                                       message.Receiver));

                SendMessageToTerminal(message, client, sendToClientCompleteHandler);
            }
            else
            {
                SendingByRuler(entity, client, message, clients, queue, sendToClientCompleteHandler, outPutSystemMessageHandler);
            }
        }
Esempio n. 11
0
        protected virtual string Working(string token, NameValueCollection parameters)
        {
            LogCommonHelper.WriteLog("Working开始处理");

            parameters.Remove("key");
            parameters.Add("access_token", token);
            UpdateParameters(parameters);
            string url = GetUrl();

            LogCommonHelper.WriteLog("url:" + url);

            string method = GetMethod();

            LogCommonHelper.WriteLog("method:" + method);

            string data = GetFromWebRequest(url, method, parameters);

            LogCommonHelper.WriteLog("data:" + data);

            return(data);
        }
Esempio n. 12
0
        public string Save(string postStr, string signature, string timestamp, string nonce)
        {
            try
            {
                #region ==== 微信數據處理 ====
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(postStr);

                TEntity entity = new TEntity();

                Type           type          = typeof(TEntity);
                PropertyInfo[] propertyinfos = type.GetProperties();
                foreach (var item in propertyinfos)
                {
                    var list = xml.GetElementsByTagName(item.Name);
                    if (item.Name == "ID")
                    {
                        item.SetValue(entity, 0, null);
                    }
                    else
                    {
                        string v = string.Empty;
                        for (int i = 0; i < list.Count; i++)
                        {
                            if (list[i].ChildNodes[0].NodeType == System.Xml.XmlNodeType.CDATA)
                            {
                                v = list[i].ChildNodes[0].Value;
                            }
                            else
                            {
                                v = list[i].InnerText;
                            }

                            item.SetValue(entity, GetValueOfType(item, v), null);
                        }
                    }
                }

                LogCommonHelper.WriteLog("ToUserName:" + entity.ToUserName);

                WxAccountRepository cr = new WxAccountRepository();
                var user = cr.FindByExpression(m => m.WeiXinNo == entity.ToUserName).FirstOrDefault();
                if (user == null)
                {
                    LogCommonHelper.WriteLog("开始处理微信标识");
                    var users = cr.FindByExpression(m => m.TokenStatus == 0).ToList();
                    if (users == null)
                    {
                        return(string.Empty);
                    }

                    foreach (var item in users)
                    {
                        string[] ArrTmp = { item.Token, timestamp, nonce };
                        Array.Sort(ArrTmp);
                        string tmpStr = string.Join("", ArrTmp);
                        tmpStr = CryptHelper.SHA1(tmpStr);
                        tmpStr = tmpStr.ToLower();

                        if (tmpStr == signature)
                        {
                            LogCommonHelper.WriteLog("标识处理成功,开始更新信息");
                            item.WeiXinNo    = entity.ToUserName;
                            item.TokenStatus = 2;
                            cr.Update(item.ID, item);
                            LogCommonHelper.WriteLog("更新信息完成");
                            break;
                        }
                    }
                }

                if (user.IsSaveRecord)
                {
                    TRepository respository = new TRepository();
                    respository.Add(entity);
                }
                #endregion

                OutReplyTextHandler      outReplyTextHandler      = new OutReplyTextHandler(OutReplyText);
                OutReplyImageTextHandler outReplyImageTextHandler = new OutReplyImageTextHandler(OutReplyImageText);

                return(SendingMessage(entity, user, outReplyTextHandler, outReplyImageTextHandler));
            }
            catch (Exception ex)
            {
                LogCommonHelper.WriteLog("Exception:" + ex.InnerException.Message);
                return(string.Empty);
            }
        }
Esempio n. 13
0
        protected virtual string SendingMessage(TEntity entity, WxAccountEntity user,
                                                OutReplyTextHandler outReplyTextHandler, OutReplyImageTextHandler outReplyImageTextHandler)
        {
            LogCommonHelper.WriteLog("开始回复");

            var    db       = CoreDBContext.GetContext();
            string keywords = this.GetKeyword(entity);

            LogCommonHelper.WriteLog("Keywords:" + keywords);

            if (string.IsNullOrEmpty(keywords))
            {
                return(string.Empty);
            }
            LogCommonHelper.WriteLog("读取文本配置");

            string[] kws = keywords.Split(new char[] { ' ' });

            var tReply = (from x in db.Set <WxReplyTextEntity>()
                          where x.UserName == user.UserName &&
                          x.Keyword != "subscribe" &&
                          x.MatchType == 1 ? (from y1 in
                                              (from x1 in db.Set <WxReplyTextEntity>()
                                               where x1.ID == x.ID
                                               select x1)
                                              .First()
                                              .Keyword
                                              .Split(new char[] { ' ' }).ToList()
                                              where y1 == keywords
                                              select y1).Any()
                                             : (from x2 in db.Set <WxReplyTextEntity>()
                                                where x2.ID == x.ID
                                                select x2)
                          .First()
                          .Keyword
                          .Split(new char[] { ' ' })
                          .Contains(keywords)
                          select x).FirstOrDefault();

            if (tReply != null)
            {
                return(this.OutReplyText(entity, tReply));
            }
            else
            {
                var itReply = (from x in db.Set <WxReplyImageTextEntity>()
                               where x.UserName == user.UserName &&
                               x.Keyword != "subscribe" &&
                               x.MatchType == 1 ? (from y1 in
                                                   (from x1 in db.Set <WxReplyImageTextEntity>()
                                                    where x1.ID == x.ID
                                                    select x1)
                                                   .First()
                                                   .Keyword
                                                   .Split(new char[] { ' ' }).ToList()
                                                   where y1 == keywords
                                                   select y1).Any()
                                                  : (from x2 in db.Set <WxReplyImageTextEntity>()
                                                     where x2.ID == x.ID
                                                     select x2)
                               .First()
                               .Keyword
                               .Split(new char[] { ' ' })
                               .Contains(keywords)
                               select x).FirstOrDefault();

                if (itReply != null)
                {
                    List <WxReplyImageTextEntity> itReplyList = new List <WxReplyImageTextEntity>();
                    if (!string.IsNullOrEmpty(itReply.WithIds))
                    {
                        string[] withIds = itReply.WithIds.Split(new char[] { '|' });
                        itReplyList = (from m in db.Set <WxReplyImageTextEntity>()
                                       where m.UserName == user.UserName &&
                                       m.Keyword != "subscribe" &&
                                       withIds.Contains(SqlFunctions.StringConvert((decimal)m.ID).Trim())
                                       select m).ToList();
                    }

                    itReplyList.Insert(0, itReply);
                    return(this.OutReplyImageText(entity, itReplyList));
                }
            }

            return(string.Empty);
        }
Esempio n. 14
0
        protected override void SendingByRuler(DialogInfoEntity entity,
                                               SocketP2PEntity client, SocketP2PMessageEntity message,
                                               List <SocketP2PEntity> clients, List <SocketP2PEntity> queue,
                                               SendToClientCompleteHandler sendToClientCompleteHandler, OutPutSystemMessageHandler outPutSystemMessageHandler)
        {
            if (message.Data.Replace(" ", "").ToLower() == "exitall")
            {
                LogCommonHelper.WriteLog("客服全部退出");
                clients.RemoveAll(x => x.Sender == message.Sender && (x.Owner == message.Owner || x.WeiXinNo == message.WeiXinNo));
            }
            else if (message.Data.Replace(" ", "").ToLower() == "exit")
            {
                LogCommonHelper.WriteLog(string.Format("客服({0})退出", message.Sender));
                clients.RemoveAll(x => x.Sender == message.Sender && x.Receiver == message.Receiver);
            }
            else
            {
                LogCommonHelper.WriteLog("由客服发来的消息,发给访客" + message.Receiver);

                var customer = clients.Where(x => x.Sender == message.Receiver).FirstOrDefault();
                if (customer != null)
                {
                    try
                    {
                        LogCommonHelper.WriteLog("开始向访客发送消息");
                        // 记录最后通话时间
                        customer.LastTalkTime = DateTime.Now;

                        var PreparingMessageEntity = NewP2PMessage();
                        PreparingMessageEntity.Sender   = customer.Receiver;
                        PreparingMessageEntity.Receiver = customer.Sender;
                        PreparingMessageEntity.Data     = message.Data;
                        PreparingMessageEntity.Owner    = customer.Owner;
                        PreparingMessageEntity.Identity = "SERVANT";
                        PreparingMessageEntity.WeiXinNo = customer.WeiXinNo;
                        PreparingMessageEntity.OpenId   = customer.OpenId;

                        SendMessageToTerminal(PreparingMessageEntity, customer, sendToClientCompleteHandler);
                    }
                    catch (SocketException ex)
                    {
                        client.Socket.Close();
                        clients.Remove(client);
                        outPutSystemMessageHandler(ex.Message);
                    }
                }
                else
                {
                    var servant = clients.Where(x => x.Receiver == message.Receiver).FirstOrDefault();
                    if (servant != null)
                    {
                        try
                        {
                            LogCommonHelper.WriteLog("向客服发送访客断线的消息");

                            var PreparingMessageEntity = NewP2PMessage();
                            PreparingMessageEntity.Sender   = null;
                            PreparingMessageEntity.Receiver = servant.Sender;
                            PreparingMessageEntity.Identity = "SERVER";
                            PreparingMessageEntity.Data     = string.Format("访客({0})已经断线,请您等待其他的访客请求...", message.Receiver);
                            PreparingMessageEntity.Owner    = servant.Owner;
                            PreparingMessageEntity.WeiXinNo = servant.WeiXinNo;
                            PreparingMessageEntity.OpenId   = servant.OpenId;

                            servant.Receiver = null;
                            SendMessageToTerminal(PreparingMessageEntity, servant, sendToClientCompleteHandler);
                        }
                        catch (SocketException ex)
                        {
                            client.Socket.Close();
                            clients.Remove(client);
                            outPutSystemMessageHandler(ex.Message);
                        }
                    }
                }
            }
        }
Esempio n. 15
0
        protected override string SendingMessage(WxSubscribeEventEntity entity, WxAccountEntity user,
                                                 OutReplyTextHandler OutReplyTextHandler, OutReplyImageTextHandler OutReplyImageTextHandler)
        {
            LogCommonHelper.WriteLog("开始处理关注/取消数据");
            var db = CoreDBContext.GetContext();
            //讀取配置
            var config = (from x in db.Set <WxSubscribeConfigEntity>()
                          where x.UserName == user.UserName
                          select x).FirstOrDefault();

            if (config != null)
            {
                if (config.IsSaveUser)
                {
                    // 记录到服务的数据库
                    WxSubUserEntity subUser = new WxSubUserEntity();
                    subUser.UserName = user.UserName;
                    subUser.OpenId   = entity.FromUserName;
                    WxSubUserRepository repository = new WxSubUserRepository();
                    repository.Add(subUser);

                    // 记录到别人的数据库
                    if (string.IsNullOrWhiteSpace(config.SaveUrl) == false)
                    {
                        Uri    uri = new Uri(config.SaveUrl);
                        string url = string.Empty;
                        if (string.IsNullOrEmpty(uri.Query))
                        {
                            url = string.Format("{0}?openid={1}", config.SaveUrl, entity.FromUserName);
                        }
                        else
                        {
                            url = string.Format("{0}&openid={1}", config.SaveUrl, entity.FromUserName);
                        }

                        if (!string.IsNullOrEmpty(url))
                        {
                            string html = WebHelper.GetFormWebRequest(url);
                        }
                    }
                }

                // 发送消息
                WxReplyTextEntity             textReply  = null;
                List <WxReplyImageTextEntity> imageReply = null;
                switch (config.ReplyType.ToLower())
                {
                case "text":
                    textReply = (from x in db.Set <WxReplyTextEntity>()
                                 where x.UserName == user.UserName &&
                                 x.Keyword == "subscribe"
                                 select x).FirstOrDefault();
                    break;

                case "imagetext":
                    var itReply = (from x in db.Set <WxReplyImageTextEntity>()
                                   where x.UserName == user.UserName &&
                                   x.Keyword == "subscribe"
                                   select x).FirstOrDefault();

                    if (itReply != null && !string.IsNullOrEmpty(itReply.WithIds))
                    {
                        string[] withIds = itReply.WithIds.Split(new char[] { '|' });
                        imageReply = (from x in db.Set <WxReplyImageTextEntity>()
                                      where x.UserName == user.UserName &&
                                      withIds.Contains(SqlFunctions.StringConvert((decimal)x.ID).Trim())
                                      select x).ToList();
                    }

                    imageReply.Insert(0, itReply);
                    break;
                }

                if (textReply != null)
                {
                    return(OutReplyTextHandler(entity, textReply));
                }

                if (imageReply != null)
                {
                    return(OutReplyImageTextHandler(entity, imageReply));
                }
            }

            return(string.Empty);
        }
Esempio n. 16
0
 public void SendMessageToP2PServer(SocketP2PMessageEntity entity)
 {
     LogCommonHelper.WriteLog("Ws SendMessageToP2PServer");
     this.Connection();
     message = entity;
 }
Esempio n. 17
0
        protected override void SendingByRuler(DialogInfoEntity entity, SocketP2PEntity client, SocketP2PMessageEntity message,
                                               List <SocketP2PEntity> clients, List <SocketP2PEntity> queue,
                                               SendToClientCompleteHandler sendToClientCompleteHandler,
                                               OutPutSystemMessageHandler outPutSystemMessageHandler)
        {
            LogCommonHelper.WriteLog("由访客发来的消息,发给客服" + message.Receiver);

            var servant = clients.Where(x => x.Receiver == message.Sender).FirstOrDefault();

            if (servant != null && servant.Socket.Connected)
            {
                try
                {
                    client.LastTalkTime = DateTime.Now;

                    var PreparingMessageEntity = NewP2PMessage();
                    PreparingMessageEntity.Sender   = servant.Receiver;
                    PreparingMessageEntity.Receiver = servant.Sender;
                    PreparingMessageEntity.Data     = message.Data;
                    PreparingMessageEntity.Owner    = servant.Owner;
                    PreparingMessageEntity.Identity = "CUSTOMER";
                    PreparingMessageEntity.WeiXinNo = servant.WeiXinNo;
                    PreparingMessageEntity.OpenId   = servant.OpenId;

                    SendMessageToTerminal(PreparingMessageEntity, servant, sendToClientCompleteHandler);
                }
                catch (SocketException ex)
                {
                    client.Socket.Close();
                    clients.Remove(client);
                    outPutSystemMessageHandler(ex.Message);
                }
            }
            else if (queue.Where(x => x.Sender == message.Sender).Any())
            {
                try
                {
                    client.LastTalkTime = DateTime.Now;
                    int i = queue.IndexOf(client) + 1;

                    var PreparingMessageEntity = NewP2PMessage();
                    PreparingMessageEntity.Sender   = null;
                    PreparingMessageEntity.Receiver = client.Sender;
                    PreparingMessageEntity.Identity = "SERVER";
                    PreparingMessageEntity.Data     = string.Format("您正在排队,队列序号{0},您前面还有{1}人", i, i - 1);
                    PreparingMessageEntity.Owner    = client.Owner;
                    PreparingMessageEntity.WeiXinNo = client.WeiXinNo;
                    PreparingMessageEntity.OpenId   = client.OpenId;

                    SendMessageToTerminal(PreparingMessageEntity, client, sendToClientCompleteHandler);
                }
                catch (SocketException ex)
                {
                    client.Socket.Close();
                    clients.Remove(client);
                    outPutSystemMessageHandler(ex.Message);
                }
            }
            else
            {
                try
                {
                    var PreparingMessageEntity = NewP2PMessage();
                    PreparingMessageEntity.Sender   = null;
                    PreparingMessageEntity.Receiver = client.Sender;
                    PreparingMessageEntity.Identity = "SERVER";
                    PreparingMessageEntity.Data     = "客服已经断线,请刷新后重新连接";
                    PreparingMessageEntity.Owner    = client.Owner;
                    PreparingMessageEntity.WeiXinNo = client.WeiXinNo;
                    PreparingMessageEntity.OpenId   = client.OpenId;

                    SendMessageToTerminal(PreparingMessageEntity, client, sendToClientCompleteHandler);
                }
                catch (SocketException ex)
                {
                    client.Socket.Close();
                    clients.Remove(client);
                    outPutSystemMessageHandler(ex.Message);
                }
            }
        }
Esempio n. 18
0
        protected override void RequestInfomation(HttpContext context)
        {
            LogCommonHelper.WriteLog("已经接收到数据");
            LogCommonHelper.WriteLog("IP:" + context.Request.UserHostAddress);

            //foreach (var item in context.Request.Params.AllKeys)
            //{
            //    LogCommonHelper.WriteLog(item + ":" + context.Request.Params[item]);
            //}

            string method = context.Request.HttpMethod.ToString();

            LogCommonHelper.WriteLog("Method:" + method);

            if (Equals(method.ToUpper(), "POST"))
            {
                System.IO.Stream s = context.Request.InputStream;
                byte[]           b = new byte[s.Length];
                s.Read(b, 0, (int)s.Length);
                postStr = System.Text.Encoding.UTF8.GetString(b);

                LogCommonHelper.WriteLog("接收到的信息:" + postStr);

                if (!string.IsNullOrEmpty(postStr))
                {
                    ResponseMsg(postStr, context);
                }
                else
                {
                    LogCommonHelper.WriteLog("接收到空数据");
                }
            }
            else
            {
                LogCommonHelper.WriteLog("开始验证");

                var echostr = context.Request.QueryString.Get("echoStr");
                LogCommonHelper.WriteLog("echostr:" + echostr);

                var signature = context.Request.QueryString.Get("signature");
                LogCommonHelper.WriteLog("signature:" + signature);

                var timestamp = context.Request.QueryString.Get("timestamp");
                LogCommonHelper.WriteLog("timestamp:" + timestamp);

                var nonce = context.Request.QueryString.Get("nonce");
                LogCommonHelper.WriteLog("nonce:" + nonce);

                bool flag = false;
                try
                {
                    WxIndexRepository repository = new WxIndexRepository();
                    var companys = repository.GetManyCompanyTokenFalse();

                    foreach (WxAccountEntity user in companys)
                    {
                        string token = user.Token;
                        LogCommonHelper.WriteLog("token:" + token);

                        string[] ArrTmp = { token, timestamp, nonce };

                        Array.Sort(ArrTmp);
                        string tmpStr = string.Join("", ArrTmp);
                        tmpStr = CryptHelper.SHA1(tmpStr);
                        tmpStr = tmpStr.ToLower();
                        LogCommonHelper.WriteLog("tmpStr:" + tmpStr);

                        if (tmpStr == signature)
                        {
                            LogCommonHelper.WriteLog("验证成功");
                            flag = true;
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogCommonHelper.WriteLog("Exception:" + ex.InnerException.Message);
                }

                if (flag)
                {
                    context.Response.Write(echostr);
                }
                else
                {
                    context.Response.Write(string.Empty);
                }

                context.Response.End();
            }
        }
Esempio n. 19
0
        protected override void ValidateIdentity(SocketP2PEntity client, SocketP2PMessageEntity message, List <SocketP2PEntity> clients,
                                                 List <SocketP2PEntity> queue, SendToClientCompleteHandler sendToClientCompleteHandler,
                                                 OutPutSystemMessageHandler outPutSystemMessageHandler)
        {
            LogCommonHelper.WriteLog("开始分配客服");
            LogCommonHelper.WriteLog("客户端数量:" + clients.Count);

            var servants = clients.Where(x => x.Identity == "SERVANT" &&
                                         (x.Owner == message.Owner || x.WeiXinNo == message.WeiXinNo) &&
                                         x.Receiver == null);

            LogCommonHelper.WriteLog("空闲的客服数量:" + servants.Count());

            var servant = servants.FirstOrDefault();

            bool isSuccess = false;

            if (servant != null)
            {
                #region ==== 随机分配客服 ====
                LogCommonHelper.WriteLog("随机分配客服");
                servant.Receiver = client.Sender;
                client.Receiver  = servant.Sender;
                try
                {
                    if (servant.Socket.Connected)
                    {
                        var PreparingMessageEntity = NewP2PMessage();
                        PreparingMessageEntity.Sender   = servant.Receiver;
                        PreparingMessageEntity.Receiver = servant.Sender;
                        PreparingMessageEntity.Identity = "SERVER";
                        PreparingMessageEntity.Data     = string.Format("您好,访客({0}),需要您的服务", servant.Receiver);
                        PreparingMessageEntity.Owner    = servant.Owner;
                        PreparingMessageEntity.WeiXinNo = servant.WeiXinNo;
                        PreparingMessageEntity.OpenId   = servant.OpenId;

                        SendMessageToTerminal(PreparingMessageEntity, servant, sendToClientCompleteHandler);

                        isSuccess = true;

                        if (queue.Exists(x => x.Sender == client.Sender))
                        {
                            queue.Remove(client);
                        }
                    }
                }
                catch (SocketException ex)
                {
                    servant.Socket.Close();
                    clients.Remove(servant);
                    outPutSystemMessageHandler(ex.Message);
                    return;
                }
                #endregion

                Thread.Sleep(500);

                if (isSuccess)
                {
                    #region ==== 分配成功, 向访客发送消息 ====
                    try
                    {
                        LogCommonHelper.WriteLog("分配成功,向访客发送消息");
                        // 更新发言时间
                        client.LastTalkTime = DateTime.Now;
                        // 发送消息
                        if (client.Socket.Connected)
                        {
                            var PreparingMessageEntity = NewP2PMessage();
                            PreparingMessageEntity.Sender   = client.Receiver;
                            PreparingMessageEntity.Receiver = client.Sender;
                            PreparingMessageEntity.Identity = "SERVER";
                            PreparingMessageEntity.Data     = string.Format("您好,客服({0}),正在为您服务,如果超过3分钟未发言,系统自动将您断线", client.Receiver);
                            PreparingMessageEntity.Owner    = client.Owner;
                            PreparingMessageEntity.WeiXinNo = client.WeiXinNo;
                            PreparingMessageEntity.OpenId   = client.OpenId;

                            SendMessageToTerminal(PreparingMessageEntity, client, sendToClientCompleteHandler);
                        }
                    }
                    catch (SocketException ex)
                    {
                        client.Socket.Close();
                        clients.Remove(client);
                        outPutSystemMessageHandler(ex.Message);
                    }
                    #endregion
                }
                else
                {
                    #region ==== 客服已经断线 ====
                    try
                    {
                        LogCommonHelper.WriteLog("客服已经断线,请刷新后重新连接");
                        client.Receiver = null;
                        client.DialogId = null;
                        var PreparingMessageEntity = NewP2PMessage();
                        PreparingMessageEntity.Sender   = null;
                        PreparingMessageEntity.Receiver = client.Sender;
                        PreparingMessageEntity.Identity = "SERVER";
                        PreparingMessageEntity.Data     = "客服已经断线,请刷新后重新连接";
                        PreparingMessageEntity.Owner    = client.Owner;
                        PreparingMessageEntity.WeiXinNo = client.WeiXinNo;
                        PreparingMessageEntity.OpenId   = client.OpenId;

                        SendMessageToTerminal(PreparingMessageEntity, client, sendToClientCompleteHandler);
                    }
                    catch (SocketException ex)
                    {
                        client.Socket.Close();
                        clients.Remove(client);
                        outPutSystemMessageHandler(ex.Message);
                    }
                    #endregion
                }
            }
            else
            {
                #region ==== 客服全忙 ====
                LogCommonHelper.WriteLog("客服全忙");
                try
                {
                    if (client.Socket.Connected)
                    {
                        LogCommonHelper.WriteLog("正在加入队列");
                        if (!queue.Exists(x => x.Sender == message.Sender))
                        {
                            queue.Add(client);
                        }

                        int i = queue.IndexOf(client);
                        int n = i + 1;

                        var PreparingMessageEntity = NewP2PMessage();
                        PreparingMessageEntity.Sender   = null;
                        PreparingMessageEntity.Receiver = client.Sender;
                        PreparingMessageEntity.Identity = "SERVER";
                        PreparingMessageEntity.Data     = (i == 0)
                            ? string.Format("抱歉,客服全忙。系统自动为您排队,队列序号{0},客服即将为您服务,请耐心等待", n, i)
                            : string.Format("抱歉,客服全忙。系统自动为您排队,队列序号{0},您前面还有{1}人", n, i);
                        PreparingMessageEntity.Owner    = client.Owner;
                        PreparingMessageEntity.WeiXinNo = client.WeiXinNo;
                        PreparingMessageEntity.OpenId   = client.OpenId;

                        SendMessageToTerminal(PreparingMessageEntity, client, sendToClientCompleteHandler);
                    }
                }
                catch (SocketException ex)
                {
                    client.Socket.Close();
                    clients.Remove(client);
                    outPutSystemMessageHandler(ex.Message);
                }
                #endregion
            }
        }