示例#1
0
        /// <summary>
        /// 从客户端接收数据
        /// </summary>
        /// <param name="clientAddress"></param>
        /// <param name="data"></param>
        public override void Receive(string clientAddress, byte[] data)
        {
            try
            {
                //解析头部信息,转换成统一的流格式:head[MsgType(1)+uid(4)+gameId(4)+serverId(4)+gzip(1)] + (len(4)+data)
                BufferReader reader = new BufferReader(data);
                string paramString = reader.ReadPacketString();
                paramString = HttpUtility.UrlDecode(paramString, Encoding.UTF8);
                int index = paramString.IndexOf("?d=");
                if (index != -1)
                {
                    index += 3;
                    paramString = paramString.Substring(index, paramString.Length - index);
                }
                PacketMessage packet = ParsePacketMessage(clientAddress, paramString, ConnectType.Tcp);
                var token = new UserToken();
                token.GameId = packet.Head.GameId;
                token.ServerId = packet.Head.ServerId;
                token.Uid = packet.Head.Uid;
                ClientConnectManager.Push(clientAddress, token);

                if (ReceiveCompleted != null)
                {
                    //分发送到游戏服
                    byte[] packData = packet.ToByte();
                    string successMsg = string.Format("{0}>>{1}接收到{2}字节!",
                        DateTime.Now.ToString("HH:mm:ss:ms"), clientAddress, data.Length);
                    ReceiveCompleted.BeginInvoke(clientAddress, packData, OnReceiveCompleted, successMsg);
                }
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("Receive form client {0} error:{1}", clientAddress, ex);
            }
        }
示例#2
0
        public override void OnReceiveTimeout(string clientAddress, byte[] receiveData)
        {
            try
            {
                BufferReader reader = new BufferReader(receiveData);
                string paramString = reader.ReadPacketString();
                paramString = HttpUtility.UrlDecode(paramString, Encoding.UTF8);
                int index = paramString.IndexOf("?d=");
                if (index != -1)
                {
                    index += 3;
                    paramString = paramString.Substring(index, paramString.Length - index);
                }
                PacketMessage receivePacket = ParsePacketMessage(clientAddress, paramString, ConnectType.Tcp);
                var recHead = receivePacket.Head;

                int errorCode = LanguageHelper.GetLang().ErrorCode;
                string errorMsg = LanguageHelper.GetLang().RequestTimeout;
                MessageHead head = new MessageHead(recHead.MsgId, recHead.ActionId, "st", errorCode, errorMsg);
                head.HasGzip = true;
                MessageStructure ds = new MessageStructure();
                ds.WriteBuffer(head);
                byte[] data = ds.ReadBuffer();
                OnSendCompleted(clientAddress, data);
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("Send to client {0} timeout error:{1}", clientAddress, ex);
            }
        }
示例#3
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="session"></param>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public byte[] Receive(string session, byte[] buffer)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            BufferReader reader = new BufferReader(buffer);
            string routeName = "";
            string paramString = reader.ReadPacketString();

            #if DEBUG
            //todo trace
            TraceLog.ReleaseWrite("Tcp param:{0}", paramString);
            #endif
            bool isRoute = false;
            if (!string.IsNullOrEmpty(paramString) && paramString.StartsWith("route:", StringComparison.CurrentCultureIgnoreCase))
            {
                //检查参数格式:route:name?d=param
                isRoute = true;
                string[] paramArray = paramString.Split('?');
                if (paramArray.Length == 2)
                {
                    routeName = paramArray[0].Replace("route:", "");
                    paramString = "?" + paramArray[1];
                }
            }
            paramString = HttpUtility.UrlDecode(paramString, Encoding.UTF8);
            int index = paramString.IndexOf("?d=");
            if (index != -1)
            {
                index += 3;
                paramString = paramString.Substring(index, paramString.Length - index);
            }
            var paramGeter = new ParamGeter(paramString);
            string remoteAddress = session.RemoteAddress;
            MessageHead head = ParseMessageHead(paramGeter);
            head.HasGzip = true;
            session.UserData = head;
            MessageStructure ms = new MessageStructure();
            #if DEBUG
            Console.WriteLine("{0}>>请求参数:MsgId:{1},ActionId:{2},ip:{3}", DateTime.Now.ToLongTimeString(),
                head.MsgId, head.Action, remoteAddress);

            #endif
            var settings = ParseRequestSettings(paramGeter, remoteAddress);
            settings.ParamString = paramString;
            settings.RouteName = routeName;

            byte[] sendBuffer = new byte[0];
            RequestError error = RequestError.Success;
            try
            {
                if (isRoute)
                {
                    if (CheckCallAccessLimit(remoteAddress))
                    {
                        error = RequestError.Unknown;
                        head.ErrorInfo = ErrorCallAccessLimit;
                    }
                    else
                    {
                        ServiceRequest.CallRemote(settings, out sendBuffer);
                    }
                }
                else
                {
                    ServiceRequest.Request(settings, out sendBuffer);
                }
            }
            catch (CommunicationObjectFaultedException fault)
            {
                TraceLog.WriteError("The wcfclient request faulted:{0}", fault);
                error = RequestError.Closed;
                ServiceRequest.ResetChannel(settings);
            }
            catch (Exception ex)
            {
                if (ex.InnerException is SocketException)
                {
                    var sex = ex.InnerException as SocketException;
                    TraceLog.WriteError("The wcfclient request connect:{0}-{1}", sex.SocketErrorCode, sex);
                    if (sex.SocketErrorCode == SocketError.TimedOut)
                    {
                        error = RequestError.Timeout;
                    }
                    else
                    {
                        error = RequestError.UnableConnect;
                    }
                }
                else
                {
                    TraceLog.WriteError("The wcfclient request error:{0}", ex);
                    error = RequestError.Unknown;
                }
                ServiceRequest.ResetChannel(settings);
            }
            watch.Stop();
            switch (error)
            {
                case RequestError.Success:
                    ms.WriteGzipBuffer(sendBuffer);

                    string msg = string.Format("[{0}]请求响应{1}:route={8},MsgId={2},St={3},Action-{4},error:{5}-{6},bytes:{7},响应时间:{9}ms\r\n",
                                               DateTime.Now.ToLongTimeString(),
                                               session.RemoteAddress,
                                               head.MsgId,
                                               head.St,
                                               head.Action,
                                               head.ErrorCode,
                                               head.ErrorInfo,
                                               sendBuffer.Length,
                                               routeName,
                                               (int)watch.Elapsed.TotalMilliseconds);
                    TraceLog.ReleaseWrite(msg);
            #if DEBUG
            #endif
                    Console.WriteLine(msg);

                    break;
                case RequestError.Closed:
                case RequestError.NotFindService:
                    head.ErrorInfo = ErrorNotFind;
                    DoWriteError(ms, head);
                    break;
                case RequestError.UnableConnect:
                    head.ErrorInfo = ErrorConnected;
                    DoWriteError(ms, head);
                    break;
                case RequestError.Timeout:
                    head.ErrorInfo = ErrorTimeout;
                    DoWriteError(ms, head);
                    break;
                case RequestError.Unknown:
                    DoWriteError(ms, head);
                    break;
                default:
                    throw new ArgumentOutOfRangeException("RequestError", error, "Not process RequestError enum.");
            }
            sendBuffer = ms.ReadBuffer();
            return sendBuffer;
        }
 private void ParseData(string paramString, Stream inputStream)
 {
     if (!string.IsNullOrEmpty(paramString))
     {
         RawParam = paramString;
         ParseParamString(paramString);
     }
     byte[] data = new BufferReader(inputStream).Data;
     var paramBytes = SplitBuffer(data);
     string str = _encoding.GetString(paramBytes);
     if (!string.IsNullOrEmpty(str))
     {
         if (str.StartsWith("d=")) str = "?" + str;
         if (string.IsNullOrEmpty(RawParam)) RawParam = str;
         ParseParamString(str);
     }
 }