Exemplo n.º 1
0
 /// <summary>
 /// 代理登录
 /// </summary>
 /// <param name="requestMsg">请求参数</param>
 /// <param name="head">报文头</param>
 /// <param name="client">当前连接客户端对象</param>
 /// <returns></returns>
 public string Login(string requestMsg, HeadMessage head, ClientOP client)
 {
     //ComunicationMsg sendMsg = new ComunicationMsg();
     //ErrorMessage error = new ErrorMessage();
     //HeadMessage sendHead = new HeadMessage();
     try
     {
         sendHead.Method = head.Method;
         sendHead.Token  = Guid.NewGuid().ToString().Replace("-", "");
         AgentSearchModel aSearch     = JSON.ToObject <AgentSearchModel>(requestMsg);
         string           responseMsg = "";
         if (aSearch == null)
         {
             error.ErrMsg = "没有接收到登录账号或密码";
             error.ErrNo  = "0003";
         }
         else
         {
             responseMsg = loginDal.Login(aSearch, head, out error);
             if (error.ErrNo == "0000")
             {
                 foreach (KeyValuePair <string, ClientOP> kv in WsSocket.dic_Clients)
                 {
                     if (!string.IsNullOrEmpty(aSearch.A_UserID) && kv.Value.LogName == aSearch.A_UserID)
                     {
                         ErrorMessage outErr = new ErrorMessage();
                         outErr.ErrNo  = "0000";
                         outErr.ErrMsg = "此账号已在别处登录";
                         HeadMessage outHead = new HeadMessage();
                         outHead.Method = "GoOut";
                         ComunicationMsg outSend = new ComunicationMsg();
                         outSend.Head  = JSON.ToJSON(outHead);
                         outSend.Error = JSON.ToJSON(outErr);
                         WsSocket ws = new WsSocket();
                         ws.Send(JSON.ToJSON(outSend), kv.Value.cSocket, true);
                     }
                 }
                 client.LogName = aSearch.A_UserID;
                 client.Token   = sendHead.Token;
                 client.ConTime = DateTime.Now;
                 //将成功登录的客户端添加到字典中
                 WsSocket.dic_Clients.AddOrUpdate(client.ConID, client, (key, oldv) => client);
             }
         }
         sendMsg.Head    = JSON.ToJSON(sendHead);
         sendMsg.Error   = JSON.ToJSON(error);
         sendMsg.Reponse = JSON.ToJSON(new { LoginAgent = string.IsNullOrEmpty(responseMsg) ? "{}" : responseMsg });
         return(JSON.ToJSON(sendMsg));
     }
     catch (Exception ex)
     {
         Common.LogHelper.WriteLog(typeof(LoginBLL), ex);
         error.ErrNo     = "0004";
         error.ErrMsg    = ex.Message.Replace("\r", "").Replace("\n", "");
         sendMsg.Head    = JSON.ToJSON(head);
         sendMsg.Reponse = "{}";
         sendMsg.Error   = JSON.ToJSON(error);
         return(JSON.ToJSON(sendMsg));
     }
 }
Exemplo n.º 2
0
 /// <summary>
 /// websocket数据包解析入口
 /// </summary>
 /// <param name="buffer">字节数组</param>
 /// <param name="len">长度</param>
 /// <param name="s">客户端的套接字</param>
 /// <returns>解析是否成功</returns>
 public bool Analyze(byte[] buffer, int len, ClientOP clientop)
 {
     try
     {
         Socket     cSocket   = clientop.cSocket;
         IPEndPoint ep        = (IPEndPoint)cSocket.RemoteEndPoint;
         string     ip        = ep.Address.ToString();
         string     port      = ep.Port.ToString();
         string     packetStr = Encoding.UTF8.GetString(buffer, 0, len);
         clientop.IP   = ip;
         clientop.Port = port;
         if (Regex.Match(packetStr.ToLower(), "upgrade: websocket").Value == "")                                     //当收到的数据[不是]握手包时
         {
             if (dic_clients.ContainsKey(ip) && Regex.Match(packetStr.ToLower(), "policy-file-request").Value == "") //当收到的数据[不是]flash请求策略文件时
             {
                 clientop.Pac_Msg = AnalyzeClientData(clientop, buffer, len);                                        //解析出客户端的消息
             }
             else
             {
                 if (Regex.Match(packetStr.ToLower(), "policy-file-request").Value != "")//当收到flash请求策略文件时
                 {
                     cSocket.Send(Encoding.UTF8.GetBytes("<cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"*\" /></cross-domain-policy>\0"));
                     clientop.Pac_Flash = true;
                     return(true);
                 }
                 else
                 {
                     cSocket.Send(Encoding.UTF8.GetBytes("Sorry,Not allow,Please call me number:13860436191"));
                     return(false);
                 }
             }
         }
         else
         {
             cSocket.Send(AnswerHandShake(packetStr)); //应答握手包
             clientop.Pac_Type = 101;                  //连接成功
         }
         //添加客户端入集合
         if (dic_clients.ContainsKey(ip) && clientop.Pac_Type == 101)
         {
             //同个IP重复登录(注:您也可以自己定义key的值,这里作者把IP作为key)
             SendToClient("<b>同个IP已重复登录:</b>" + "如有什么疑问,也可以联系作者,QQ:114687576", dic_clients[ip].cSocket); //发出提醒
             closeConnect(dic_clients[ip].cSocket);                                                      //关闭旧连接
             dic_clients.AddOrUpdate(ip, clientop, (key, oldv) => clientop);                             //更新最新该连接
         }
         else
         {
             dic_clients.TryAdd(ip, clientop);
         }
         return(true);
     }
     catch (Exception ex)
     {
         string strException = string.Format("{0}发生系统异常[Analyze]。\r\n{1}\r\n\r\n\r\n", DateTime.Now, ex.Message + "(" + ex.StackTrace + ")");
         File.AppendAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SystemException.log"), strException);
         return(false);
     }
 }
Exemplo n.º 3
0
 /// <summary>
 /// 队列_界面显示信息
 /// </summary>
 private void Queue_UIshow()
 {
     while (true)
     {
         ClientOP cp = null;
         WSClass.que_msgs.TryDequeue(out cp);
         if (cp != null)
         {
             syncContext.Post(rec_msg, cp);//解析并显示接收信息
         }
         Thread.Sleep(100);
     }
 }
Exemplo n.º 4
0
    /// <summary>
    /// 删除字典里的连接
    /// </summary>
    /// <param name="cp">客户端连接</param>
    private void removeConnectDic(ClientOP cp)
    {
        string   ip   = cp.IP;
        string   port = cp.Port;
        ClientOP _cp  = new ClientOP();

        if (dic_clients.ContainsKey(ip))
        {
            if (dic_clients.TryRemove(ip, out _cp))
            {
                closeConnect(cp.cSocket);
            }
        }
    }
Exemplo n.º 5
0
 /// <summary>
 /// 线程,检查客户端离线
 /// </summary>
 private static void Thread_Check_Logout()
 {
     while (true)
     {
         ClientOP cp = new ClientOP();
         foreach (KeyValuePair <string, ClientOP> kv in dic_clients)
         {
             if (!kv.Value.cSocket.Connected)//该客户端已经断开
             {
                 cp          = new ClientOP();
                 cp.Pac_Type = 8;
                 cp.IP       = kv.Key;
                 dic_clients.TryRemove(kv.Key, out cp);
                 que_msgs.Enqueue(cp);//通知离线消息
             }
         }
         Thread.Sleep(1000);
     }
 }
Exemplo n.º 6
0
        /// <summary>
        /// 初步处理接收到的报文
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="isZ">标记应答报文是否需要Gzip压缩</param>
        /// <returns></returns>
        public string StartAnalyze(string msg, ClientOP client, out bool isZ)
        {
            ComunicationMsg cmMsg                = JSON.ToObject <ComunicationMsg>(msg);
            ComunicationMsg cMsg                 = new ComunicationMsg();
            HeadMessage     hMsg                 = new HeadMessage();
            ErrorMessage    error                = new ErrorMessage();
            RequestMsg      reqMsg               = new RequestMsg();
            bool            isGoupRetMsg         = true;  //是否需要组装应答报文
            string          methodReturn         = "";
            bool            hasRequestParameters = false; //是否包含请求参数
            bool            isLoginAuth          = false; //是否通过了登录验证
            string          retMsg               = "";
            string          response             = "{}";

            isZ = true;
            HeadMessage head;

            if (cmMsg != null)
            {
                try
                {
                    reqMsg = cmMsg.Request != null?JSON.ToObject <RequestMsg>(cmMsg.Request) : reqMsg;

                    //判断应答报文是否需要压缩
                    if (reqMsg != null && !string.IsNullOrEmpty(reqMsg.IsZ) && reqMsg.IsZ == "N")
                    {
                        isZ = false;
                    }
                    //判断是否包含请求参数
                    if (reqMsg != null && !string.IsNullOrEmpty(reqMsg.RequestParams))
                    {
                        hasRequestParameters = true;
                    }
                    else
                    {
                        error.ErrNo  = "0003";
                        error.ErrMsg = "请求参数不完整。";
                    }
                    //解码报文头
                    head = JSON.ToObject <HeadMessage>(cmMsg.Head);
                    if (head != null)
                    {
                        if (string.IsNullOrEmpty(head.Account) || string.IsNullOrEmpty(head.Token) || string.IsNullOrEmpty(head.LoginID))
                        {
                            isLoginAuth   = false;
                            error.ErrMsg += " 没有通过登录验证,所以无权获取数据。";
                            error.ErrNo   = "0004";
                        }
                        else
                        {
                            foreach (KeyValuePair <string, ClientOP> kv in WsSocket.dic_Clients)
                            {
                                if (head.Account == kv.Value.LogName && head.Token == kv.Value.Token)
                                {
                                    isLoginAuth = true;
                                    break;
                                }
                            }
                            if (!isLoginAuth)
                            {
                                error.ErrMsg += " 没有通过登录验证,所以无权获取数据。";
                                error.ErrNo   = "0004";
                            }
                        }
                        string method = head.Method ?? "";
                        head.Ip     = client.IP;
                        hMsg.Method = method;
                        switch (method)
                        {
                        case "HeartBeat":    //心跳
                            error.ErrNo  = "0000";
                            error.ErrMsg = "连接正常";
                            break;

                        case "SignOut":    //登出
                            if (hasRequestParameters)
                            {
                                isGoupRetMsg = false;
                                methodReturn = loginBll.SignOut(reqMsg.RequestParams, head);
                            }
                            break;

                            #region 登录部分
                        case "Login":    //登录
                            if (hasRequestParameters)
                            {
                                isGoupRetMsg = false;
                                methodReturn = loginBll.LoginLogic(reqMsg.RequestParams, head, client);
                            }
                            break;

                        case "GetSelfCenterInfo": //获取指定代理今日下单统计
                        case "CenterPlayList":    //获取指定代理会员在线情况
                        case "GetLoginACount":    //获取指定时段内指定代理统计数据
                        case "AgentClientCount":  //获取指定时段内指定代理下会员统计数据
                        case "GetAorCAgentData":  //获取指定代理或指定会员所属代理统计数据
                        case "GetAListByID":      //根据代理ID获取指定代理数据
                            if (hasRequestParameters && isLoginAuth)
                            {
                                isGoupRetMsg = false;
                                methodReturn = loginBll.LoginLogic(reqMsg.RequestParams, head, client);
                            }
                            break;

                        case "GetPubInfo":    //获取公告
                            if (isLoginAuth)
                            {
                                isGoupRetMsg = false;
                                methodReturn = loginBll.GetPubInfo(head);
                            }
                            break;

                            #endregion
                            #region 代理列表部分
                        case "GetAllAgents":   //获取指定代理及它的直属代理列表数据
                        case "GetDeletedA":    //获取指定代理下逻辑删除的代理列表数据
                        case "AgentMatchP":    //获取指定代理相关权限
                            if (hasRequestParameters && isLoginAuth)
                            {
                                isGoupRetMsg = false;
                                methodReturn = aListBll.GetALists(reqMsg.RequestParams, head);
                            }
                            break;

                        case "InsertAgent":        //新增代理
                        case "UpdateAgent":        //修改代理
                        case "AgentModifyPwd":     //修改下级代理密码
                        case "AgentSelfModifyPwd": //修改登录代理密码
                        case "AgentPoint":         //代理上下分
                        case "AgentClear":         //代理清零
                        case "SettleOdds4Agent":   //结算代理抽水
                        case "SettleWashF4Agent":  //结算代理洗码费
                        case "DeleteAgent":        //删除代理
                            if (hasRequestParameters && isLoginAuth)
                            {
                                isGoupRetMsg = false;
                                methodReturn = aListBll.InsertAgent(reqMsg.RequestParams, head);
                            }
                            break;

                        case "GetAgentLogName":  //获取代理登录名称
                        case "GetClientLogName": //获取会员登录名称
                        case "GetSubLogName":    //获取子账号登录名称
                            if (isLoginAuth)
                            {
                                isGoupRetMsg = false;
                                methodReturn = aListBll.GetALoginID(head);
                            }
                            break;

                            #endregion
                            #region 会员列表部分
                        case "GetClntList_Invite": //获取会员列表数据
                        case "GetDeletedC":        //获取逻辑删除的会员
                            if (hasRequestParameters && isLoginAuth)
                            {
                                isGoupRetMsg = false;
                                methodReturn = clntListBll.GetClntList(reqMsg.RequestParams, head);
                            }
                            break;

                        case "GetClntOdds":    //获取会员标准赔率
                            if (isLoginAuth)
                            {
                                isGoupRetMsg = false;
                                methodReturn = clntListBll.GetClntOdds(head);
                            }
                            break;

                        case "InsertClient":     //新增会员
                        case "AllClientZero":    //直属会员清零
                        case "ClientZero":       //会员清零
                        case "ClearCard4Clnt":   //会员清卡
                        case "UpdateClient":     //修改会员
                        case "ClientModifyPwd":  //修改会员密码
                        case "ClientPoint":      //会员上下分
                        case "SettleWashF4Clnt": //结算会员洗码费
                            if (hasRequestParameters && isLoginAuth)
                            {
                                isGoupRetMsg = false;
                                methodReturn = clntListBll.ClntOperates(reqMsg.RequestParams, head);
                            }
                            break;

                            #endregion
                            #region 子账号部分
                        case "GetAgentSubs":    //获取指定代理下子账号列表数据
                            aSubBll.GetAgentSubs(reqMsg.RequestParams, head);
                            break;

                        case "InsertAgentSub":    //新增子账号
                        case "UpdateAgentSub":    //修改子账号
                        case "UpdateSubState":    //修改子账号状态
                        case "DeleteAgentSub":    //删除子账号
                            aSubBll.ASubOperates(reqMsg.RequestParams, head);
                            break;

                            #endregion
                            #region 获取报表数据部分
                        case "GetAStatistics":       //获取代理统计数据
                        case "GetADayStatistics":    //获取代理每日统计数据
                        case "GetClntStatistics":    //获取会员统计
                        case "GetClntDayStatistics": //获取会员每日统计数据
                        case "GetClntBetBills":      //获取会员下注明细
                        case "GetPointDetail":       //获取上下分明细
                        case "GetTableResult":       //获取游戏结果数据
                        case "PromotionA_Clnt4A":    //获取指定代理下的会员推广统计数据 增量
                        case "PromotionA_AllClnt4A": //获取指定代理下的会员推广统计数据 存量
                        case "H5ClntPointDetail":    //H5会员第三方上分明细
                        case "H5ClntPointSum_A":     //获取指定代理下所有H5会员第三方上分明细
                        case "RedEnvelopeSum":       //查询指定代理自己及直属代理及直属会员下红包发放合计
                        case "RedEnvelopeDetail":    //查询指定会员下红包发送明细
                        case "GetSettleAccounts":    //获取结算记录
                        case "GetWashF4Clnt":        //获取会员的洗码费统计
                        case "GetOddsWashF4Agent":   //获取代理抽水及洗码费统计
                            if (hasRequestParameters && isLoginAuth)
                            {
                                methodReturn = sBll.GetStatisticsData(reqMsg.RequestParams, head);
                            }
                            break;

                            #endregion
                            #region 获取日志记录
                        case "GetTransactions": //获取交易记录
                        case "GetLoginLog":     //获取登录日志
                        case "GetOperationLog": //获取操作日志
                            if (hasRequestParameters && isLoginAuth)
                            {
                                isGoupRetMsg = false;
                                methodReturn = sBll.GetLog(reqMsg.RequestParams, head);
                            }
                            break;

                            #endregion
                        default:
                            error.ErrNo  = "0005";
                            error.ErrMsg = "没有对应的接口:" + method;
                            break;
                        }
                    }
                    else
                    {
                        error.ErrNo  = "0003";
                        error.ErrMsg = "报文格式错误,没有收到正确的报文头";
                    }
                }
                catch (Exception ex)
                {
                    Common.LogHelper.WriteLog(typeof(AnalyzeData), ex);
                    error.ErrNo  = "0001";
                    error.ErrMsg = "系统内部错误:" + ex.Message.Replace("\r", "").Replace("\n", "");
                }
            }
            cMsg.Head    = JSON.ToJSON(hMsg);
            cMsg.Reponse = response;
            cMsg.Request = "{}";
            cMsg.Error   = JSON.ToJSON(error);
            retMsg       = isGoupRetMsg ? JSON.ToJSON(cMsg) : methodReturn;
            return(retMsg);
        }
Exemplo n.º 7
0
        public string LoginLogic(string requestMsg, HeadMessage head, ClientOP client)
        {
            sendHead.Method = head.Method ?? "";
            error.ErrNo     = "0004";
            try
            {
                AgentSearchModel aSearch     = JSON.ToObject <AgentSearchModel>(requestMsg);
                string           responseMsg = "";
                string           pId;
                if (CommonDAL.IsSubAgent(head.LoginID, out pId))
                {
                    head.LoginID = pId;//如果当前登录代理是子账号则,将此子账号的所属代理ID赋值为当前登录代理ID
                }
                if (aSearch == null)
                {
                    error.ErrMsg = "没有接收到登录账号或密码";
                    error.ErrNo  = "0003";
                }
                else
                {
                    switch (sendHead.Method)
                    {
                    case "Login":
                        sendHead.Token = Guid.NewGuid().ToString().Replace("-", "");
                        responseMsg    = loginDal.Login(aSearch, head, out error);
                        if (error.ErrNo == "0000")
                        {
                            foreach (KeyValuePair <string, ClientOP> kv in WsSocket.dic_Clients)
                            {
                                if (!string.IsNullOrEmpty(aSearch.A_UserID) && kv.Value.LogName == aSearch.A_UserID)
                                {
                                    ErrorMessage outErr = new ErrorMessage();
                                    outErr.ErrNo  = "0000";
                                    outErr.ErrMsg = "此账号已在别处登录";
                                    HeadMessage outHead = new HeadMessage();
                                    outHead.Method = "GoOut";
                                    ComunicationMsg outSend = new ComunicationMsg();
                                    outSend.Head  = JSON.ToJSON(outHead);
                                    outSend.Error = JSON.ToJSON(outErr);
                                    WsSocket ws = new WsSocket();
                                    ws.Send(JSON.ToJSON(outSend), kv.Value.cSocket, true);
                                    ws.closeConnect(kv.Value.cSocket);              //断开之前的连接
                                    ClientOP op;
                                    WsSocket.dic_Clients.TryRemove(kv.Key, out op); //将连接移除字典
                                    break;
                                }
                            }
                            client.LogName = aSearch.A_UserID;
                            client.Token   = sendHead.Token;
                            //将成功登录的客户端添加到字典中
                            WsSocket.dic_Clients.AddOrUpdate(client.ConID, client, (key, oldv) => client);
                        }
                        break;

                    case "GetSelfCenterInfo":
                        responseMsg = loginDal.GetATodayBillCount(aSearch, head, out error);
                        break;

                    case "CenterPlayList":
                        responseMsg = loginDal.GetOnlineClntList(aSearch, head, out error);
                        break;

                    case "GetLoginACount":
                        responseMsg = loginDal.GetACountByDate(aSearch, head, out error);
                        break;

                    case "AgentClientCount":
                        responseMsg = loginDal.GetAClntCount(aSearch, head, out error);
                        break;

                    case "GetAorCAgentData":
                        responseMsg = loginDal.GetAorCAgentData(aSearch, head, out error);
                        break;

                    case "GetAListByID":
                        responseMsg = loginDal.GetAListByID(aSearch, head, out error);
                        break;

                    default:
                        responseMsg = "";
                        break;
                    }
                }
                sendMsg.Head    = JSON.ToJSON(sendHead);
                sendMsg.Error   = JSON.ToJSON(error);
                sendMsg.Reponse = JSON.ToJSON(new { JsonData = (string.IsNullOrEmpty(responseMsg)) ? "{}" : responseMsg });
                return(JSON.ToJSON(sendMsg));
            }
            catch (Exception ex)
            {
                Common.LogHelper.WriteLog(typeof(LoginBLL), ex);
                error.ErrMsg    = ex.Message.Replace("\r", "").Replace("\n", "");
                sendMsg.Head    = JSON.ToJSON(sendHead);
                sendMsg.Reponse = "{}";
                sendMsg.Error   = JSON.ToJSON(error);
                return(JSON.ToJSON(sendMsg));
            }
        }
Exemplo n.º 8
0
    /// <summary>
    /// 解析数据包
    /// </summary>
    /// <param name="buffer">数据包</param>
    /// <param name="len">长度</param>
    /// <returns></returns>
    private string AnalyzeClientData(ClientOP clientop, byte[] buffer, int len)
    {
        bool mask   = false;
        int  lodlen = 0;

        if (len < 2)
        {
            return(string.Empty);
        }
        clientop.Pac_Fin = (buffer[0] >> 7) > 0;
        if (!clientop.Pac_Fin)
        {
            return(string.Empty);
        }
        clientop.Pac_Type = buffer[0] & 0xF;
        if (clientop.Pac_Type == 10)//心跳包(IE10及以上特有,不处理即可)
        {
            return(string.Empty);
        }
        else if (clientop.Pac_Type == 8)//退出包
        {
            removeConnectDic(clientop);
            return(string.Empty);
        }
        mask   = (buffer[1] >> 7) > 0;
        lodlen = buffer[1] & 0x7F;
        byte[] loddata;
        byte[] masks = new byte[4];

        if (lodlen == 126)
        {
            Array.Copy(buffer, 4, masks, 0, 4);
            lodlen  = (UInt16)(buffer[2] << 8 | buffer[3]);
            loddata = new byte[lodlen];
            Array.Copy(buffer, 8, loddata, 0, lodlen);
        }
        else if (lodlen == 127)
        {
            Array.Copy(buffer, 10, masks, 0, 4);
            byte[] uInt64Bytes = new byte[8];
            for (int i = 0; i < 8; i++)
            {
                uInt64Bytes[i] = buffer[9 - i];
            }
            lodlen = (int)BitConverter.ToUInt64(uInt64Bytes, 0);

            loddata = new byte[lodlen];
            try
            {
                for (int i = 0; i < lodlen; i++)
                {
                    loddata[i] = buffer[i + 14];
                }
            }
            catch { }
        }
        else
        {
            Array.Copy(buffer, 2, masks, 0, 4);
            loddata = new byte[lodlen];
            Array.Copy(buffer, 6, loddata, 0, lodlen);
        }
        for (var i = 0; i < lodlen; i++)
        {
            loddata[i] = (byte)(loddata[i] ^ masks[i % 4]);
        }
        return(Encoding.UTF8.GetString(loddata));
    }
Exemplo n.º 9
0
    private void ProcessReceive(SocketAsyncEventArgs receiveEventArg)//接收数据
    {
        if (receiveEventArg.SocketError != SocketError.Success || receiveEventArg.BytesTransferred == 0)
        {
            closeConnect(receiveEventArg.AcceptSocket);
            receiveEventArg = null;
            return;
        }
        int len = receiveEventArg.BytesTransferred;//接收到的数据包长度

        byte[] data_pac = new byte[len];
        Array.Copy(receiveEventArg.Buffer, receiveEventArg.Offset, data_pac, 0, len);//将接收到的数据包放入data_pac中
        Func <bool, byte[]> appendData = (ok) =>
        {
            byte[] newdata;
            if (receiveEventArg.UserToken != null)
            {
                byte[] tmp = (byte[])receiveEventArg.UserToken;
                newdata = new byte[len + tmp.Length];
                Array.Copy(tmp, 0, newdata, 0, tmp.Length);
                Array.Copy(data_pac, 0, newdata, tmp.Length, len);
                if (ok)//true时表示所有数据接收完毕
                {
                    receiveEventArg.UserToken = null;
                }
            }
            else
            {
                newdata = data_pac;
            }
            return(newdata);
        };

        if (receiveEventArg.AcceptSocket.Available != 0)
        {
            receiveEventArg.UserToken = appendData(false);
        }
        else
        {
            data_pac = appendData(true);
            string   msg = "";
            ClientOP cp  = new ClientOP();
            cp.cSocket = receiveEventArg.AcceptSocket;
            if (Analyze(data_pac, len, cp))
            {
                if (!cp.Pac_Flash)        //当为flash请求策略文件时不加入消息队列
                {
                    que_msgs.Enqueue(cp); //将接收的消息加入队列
                }
                msg = cp.Pac_Msg;
                if (msg != "")
                {
                    Send(cp.cSocket, "<b>服务端成功收到你的消息:</b>" + replaceSpecStr(msg));
                }
                //SendToClient("<span style='color:green;'>机器人</span>:" + getRobotAnswer(msg), receiveEventArg.AcceptSocket);
                if (cp.Pac_Type == 101)
                {
                    Send(cp.cSocket, "<b>服务端主动向你推送:</b>" + " <span style='font-size:20px;'>点击进入" +
                         "<a style='font-weight:900;font-size:16px;' href='http://www.blue-zero.com/chat/' target='_blank'>" +
                         "【聊天室】[围观]</a>,使用websocket开发,支持一对一私聊和一对多公聊</span>");
                }
            }
            else
            {
                cp = null;
                closeConnect(receiveEventArg.AcceptSocket);
            }
        }
        StartReceive(receiveEventArg);//继续等待下一次接收数据
    }
Exemplo n.º 10
0
 /// <summary>
 /// 解析数据包
 /// </summary>
 /// <param name="buffer"></param>
 /// <param name="len"></param>
 /// <param name="client"></param>
 /// <returns></returns>
 public bool Analyze(byte[] buffer, int len, ClientOP client)
 {
     try
     {
         Socket     cSocket  = client.cSocket;
         IPEndPoint endPoint = (IPEndPoint)cSocket.RemoteEndPoint;
         string     ip       = endPoint.Address.ToString(); //获取Ip地址
         string     port     = endPoint.Port.ToString();    //获取端口
         string     connID   = ip + ":" + port;
         string     pacStr   = Encoding.UTF8.GetString(buffer, 0, len);
         client.IP    = ip;
         client.Port  = port;
         client.ConID = connID;
         if (Regex.Match(pacStr.ToLower(), "upgrade: websocket").Value == "")                                         //当前收到的不是握手包
         {
             if (dic_Clients.ContainsKey(connID) && Regex.Match(pacStr.ToLower(), "policy-file-request").Value == "") //当收到的数据[不是]flash请求策略文件时
             {
                 client.Pac_Msg = AnalyzeClientData(client, buffer, len);                                             //解析出客户端的消息
             }
             else
             {
                 if (Regex.Match(pacStr.ToLower(), "policy-file-request").Value != "")//当收到flash请求策略文件时
                 {
                     cSocket.Send(Encoding.UTF8.GetBytes("<cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"*\" /></cross-domain-policy>\0"));
                     client.Pac_Flash = true;
                     return(true);
                 }
                 else
                 {
                     cSocket.Send(Encoding.UTF8.GetBytes("Sorry,Not allow,Please call me number:13888888888"));
                     return(false);
                 }
             }
         }
         else
         {
             cSocket.Send(AnswerHandShake(pacStr));
             client.Pac_Type = 101;//连接成功
         }
         if (dic_Clients.ContainsKey(connID) && client.Pac_Type == 101)
         {
             //同个IP重复登录(注:您也可以自己定义key的值,这里把IP作为key)
             Send("同个IP已重复登录:", dic_Clients[connID].cSocket, false); //发出提醒
             closeConnect(dic_Clients[connID].cSocket);              //关闭旧连接
         }
         else
         {
             if (dic_Clients.TryAdd(connID, client))
             {
                 if (!client.Pac_Flash)
                 {
                     que_msgs.Enqueue(client);
                 }
             }
         }
         return(true);
     }
     catch (Exception ex)
     {
         LogHelper.WriteLog(typeof(WsSocket), ex);
         return(false);
     }
 }
Exemplo n.º 11
0
 /// <summary>
 /// 接收数据
 /// </summary>
 /// <param name="reciveEventArgs"></param>
 private void ProcessRecive(SocketAsyncEventArgs reciveEventArgs)
 {
     try
     {
         #region 处理接收到的UserToken
         //如果连接不正常,或者接收到的数据长度为0 则主动断开连接
         if (reciveEventArgs.SocketError != SocketError.Success || reciveEventArgs.BytesTransferred == 0)
         {
             closeConnect(reciveEventArgs.AcceptSocket);
             reciveEventArgs = null;
             return;
         }
         int    len      = reciveEventArgs.BytesTransferred;//记录接收到的数据包长度
         byte[] data_pac = new byte[len];
         Array.Copy(reciveEventArgs.Buffer, reciveEventArgs.Offset, data_pac, 0, len);
         Func <bool, byte[]> appendData = (ok) =>
         {
             byte[] newData;
             if (reciveEventArgs.UserToken != null)
             {
                 byte[] tmp = (byte[])reciveEventArgs.UserToken;
                 newData = new byte[len + tmp.Length];
                 Array.Copy(tmp, 0, newData, 0, tmp.Length);
                 Array.Copy(data_pac, 0, newData, tmp.Length, len);
                 if (ok)
                 {
                     reciveEventArgs.UserToken = null;
                 }
             }
             else
             {
                 newData = data_pac;
             }
             return(newData);
         }; //匿名方法appendData结束
         if (reciveEventArgs.AcceptSocket.Available != 0)
         {
             reciveEventArgs.UserToken = appendData(false);
         }
         else
         {
             data_pac = appendData(true);
             ClientOP client = new ClientOP();//记录当前连接过来的客户端对象
             client.cSocket = reciveEventArgs.AcceptSocket;
             if (Analyze(data_pac, len, client))
             {
                 string msg = client.Pac_Msg;
                 if (!string.IsNullOrEmpty(msg))
                 {
                     string      decodeMsg  = ZipHelper.GZipDecompressString(msg);//将接收到的数据进行Gizp解压
                     AnalyzeData analzeData = new AnalyzeData();
                     bool        isZ;
                     string      sendMsg = analzeData.StartAnalyze(decodeMsg, client, out isZ);
                     Send(sendMsg, client.cSocket, isZ);
                     //Send(decodeMsg, client.cSocket);
                 }
                 if (client.Pac_Type == 101)
                 {
                     Send("socket连接成功", client.cSocket, false);
                 }
             }
             else//Analyze方法的else
             {
                 Send("数据解析失败", client.cSocket, false);
                 client = null;
                 closeConnect(reciveEventArgs.AcceptSocket);
                 dic_Clients.TryRemove(client.ConID, out client);
                 reciveEventArgs.AcceptSocket = null;
             }//Analyze方法的if-else结束
         }
         #endregion
     }
     catch (Exception ex)
     {
         LogHelper.WriteLog(typeof(WsSocket), ex);
     }
     finally
     {
         if (reciveEventArgs != null && reciveEventArgs.AcceptSocket != null)
         {
             StartRecive(reciveEventArgs);//继续处理接收到的数据
         }
     }
 }
Exemplo n.º 12
0
        /// <summary>
        /// 在UI上解析并显示接收的信息
        /// </summary>
        /// <param name="msg"></param>
        private void rec_msg(object msg)
        {
            ClientOP cp      = (ClientOP)msg;
            int      type    = cp.Pac_Type;
            string   str_msg = cp.Pac_Msg;
            string   ip      = cp.IP;
            string   port    = cp.Port;
            DateTime dt      = cp.Time;

            Action Newlogin = () =>//新连接的客户端
            {
                ListViewItem lvi = new ListViewItem("");
                lvi.SubItems.Add(ip);
                lvi.SubItems.Add(dt.ToString("yyyy/MM/dd HH:mm:ss"));
                lvi.SubItems.Add("登录");
                lvi.UseItemStyleForSubItems = false;
                lvi.SubItems[0].BackColor   = Color.LightBlue;//登录时颜色标注
                lvi.SubItems[3].ForeColor   = Color.Blue;
                list_clients.Items.Add(lvi);
                ThreadPool.QueueUserWorkItem(new WaitCallback(Thread_GetAddress), ip);
            };

            if (!WSClass.dic_clients.ContainsKey(ip) && type != 8)
            {
                Newlogin();
            }
            else
            {
                ListViewItem lvi = isinList(ip);
                if (lvi != null)
                {
                    lvi.SubItems[2].Text = dt.ToString("yyyy/MM/dd HH:mm:ss");
                    if (type != 8)
                    {
                        if (type == 1)//文本消息包
                        {
                            lvi.SubItems[0].BackColor = Color.LightGreen;
                        }
                        else if (type == 101)//连接成功包
                        {
                            lvi.SubItems[0].BackColor = Color.LightBlue;
                        }
                        lvi.SubItems[3].Text      = "在线";
                        lvi.SubItems[3].ForeColor = Color.Green;
                    }
                    else
                    {
                        lvi.SubItems[3].Text      = "离线";
                        lvi.SubItems[3].ForeColor = Color.Red;
                    }
                }
                else
                {
                    if (type != 8)
                    {
                        Newlogin();
                    }
                }
            }
            if (str_msg != string.Empty)
            {
                str_msg = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " - " + str_msg + "\n";
                UpdateOrAddMsg(ip, str_msg, dic_rec);                //添加信息到dic_rec字典中
            }
            if (sel_item != null && sel_item.SubItems[1].Text == ip) //当选中的客户端与接收到的客户端一致时,显示信息
            {
                if (str_msg != string.Empty)
                {
                    rbox_rec.AppendText(str_msg);
                    rbox_rec.SelectionStart = rbox_rec.Text.Length;
                    rbox_rec.ScrollToCaret(); //自动滚动
                }
            }
        }