public void Send(byte[] data, SocketPackage package)
    {
        if (data == null)
        {
            return;
        }
        lock (_sendList)
        {
            _sendList.Add(package);
        }

        try
        {
            PostSend(data);
            //UnityEngine.Debug.Log("Socket send actionId:" + package.ActionId + ", msgId:" + package.MsgId + ", send result:" + bRet);
        }
        catch (Exception ex)
        {
            UnityEngine.Debug.Log("Socket send actionId: " + package.ActionId + " error" + ex);
            package.ErrorCode = (int)ErrorCode.ConnectError;
            package.ErrorMsg  = ex.ToString();
            lock (_receiveQueue)
            {
                _receiveQueue.Enqueue(package);
            }
            lock (_sendList)
            {
                _sendList.Remove(package);
            }
        }
    }
Exemple #2
0
 private void Update()
 {
     if (mSocket != null)
     {
         mSocket.ProcessTimeOut();
         SocketPackage data = mSocket.Dequeue();
         if (data != null)
         {
             OnSocketRespond(data);
         }
         data = mSocket.DequeuePush();
         if (data != null)
         {
             OnPushCallback(data);
         }
     }
     lock (mStatusList)
     {
         if (mStatusList.Count > 0)
         {
             for (int i = 0; i < mStatusList.Count; i++)
             {
                 Dispatch(mStatusList[i]);
             }
             mStatusList.Clear();
         }
     }
 }
    public void ProcessTimeOut()
    {
        SocketPackage findPackage = null;

        lock (_sendList)
        {
            foreach (SocketPackage package in _sendList)
            {
                if (DateTime.Now.Subtract(package.SendTime).TotalSeconds > TimeOut)
                {
                    package.ErrorCode = (int)ErrorCode.TimeOutError;
                    package.ErrorMsg  = "TimeOut";
                    findPackage       = package;
                    break;
                }
            }
        }
        if (findPackage != null)
        {
            lock (_receiveQueue)
            {
                _receiveQueue.Enqueue(findPackage);
            }
            lock (_sendList)
            {
                _sendList.Remove(findPackage);
            }
        }
    }
    public void ProcessTimeOut()
    {
        SocketPackage findPackage = null;

        lock (_sendList)
        {
            for (int i = 0; i < _sendList.Count; i++)
            {
                if (DateTime.Now.Subtract(_sendList[i].SendTime).TotalSeconds > TimeOut)
                {
                    _sendList[i].ErrorCode = (int)ErrorCode.TimeOutError;
                    _sendList[i].ErrorMsg  = "TimeOut";
                    Debug.LogError("手动处理了一个超时的消息 消息id=" + _sendList[i].ActionId);
                    findPackage = _sendList[i];
                    break;
                }
            }
        }
        if (findPackage != null)
        {
            lock (_receiveQueue)
            {
                _receiveQueue.Enqueue(findPackage);
            }
            lock (_sendList)
            {
                _sendList.Remove(findPackage);
            }
        }
    }
Exemple #5
0
    public void Request(byte[] data, SocketPackage package)
    {
        if (data == null)
        {
            return;
        }
        lock (sendList)
        {
            sendList.Add(package);
        }

        try
        {
            bool bRet = Send(data);
            UnityEngine.Debug.Log("Socket Request Id:" + package.ActionId.ToString() + " " + package.MsgId.ToString() + "send:" + bRet.ToString());
        }
        catch (System.Exception ex)
        {
            UnityEngine.Debug.Log("Request error" + ex.ToString());
            package.ErrorCode = (int)ErrorCode.eConnectError;
            package.ErrorMsg  = ex.ToString();
            lock (receiveQueue)
            {
                receiveQueue.Enqueue(package);
            }
            lock (sendList)
            {
                sendList.Remove(package);
            }
        }
    }
Exemple #6
0
    /// <summary>
    /// parse input data
    /// </summary>
    /// <param name="gameAction"></param>
    /// <param name="actionParam"></param>
    /// <param name="formater"></param>
    /// <param name="bShowLoading"></param>
    private void SocketRequest(GameAction gameAction, Google.Protobuf.IMessage pbData, IHeadFormater formater, bool bShowLoading)
    {
        if (mSocket == null)
        {
            string   url = NetWriter.GetUrl();
            string[] arr = url.Split(new char[] { ':' });
            if (arr.Length != 2)
            {
                Debug.LogError("Url is error:" + url);
                return;
            }
            int nPort = int.Parse(arr[1]);
            mSocket = new SocketConnect(arr[0], nPort, formater);
        }
        gameAction.Head.MsgId = NetWriter.MsgId - 1;

        SocketPackage package = new SocketPackage();

        package.MsgId        = gameAction.Head.MsgId;
        package.ActionId     = gameAction.ActionId;
        package.ActionRespId = gameAction.Head.ActionRespId;
        package.Action       = gameAction;
        package.HasLoading   = bShowLoading;
        package.SendTime     = DateTime.Now;
        byte[] data = gameAction.Send(pbData);
        NetWriter.resetData();
        if (bShowLoading)
        {
            RequestDelegate(Status.eStartRequest);
        }
        mSocket.Send(data, package);
    }
Exemple #7
0
    /// <summary>
    /// parse input data
    /// </summary>
    /// <param name="url"></param>
    /// <param name="callback"></param>
    /// <param name="ud"></param>
    public void SocketRequest(int actionId, INetCallback callback, object userData, bool bShowLoading)
    {
        if (mSocket == null)
        {
            string strUrl = NetWriter.GetUrl();
            Debug.Log("url" + strUrl);
            string[] arr   = strUrl.Split(new char[] { ':' });
            int      nPort = int.Parse(arr[1]);
            mSocket = new SocketConnect(arr[0], nPort);
        }
        NetWriter writer = NetWriter.Instance;

        writer.writeInt32("actionId", actionId);
        byte[]        data    = NetWriter.Instance.PostData();
        SocketPackage package = new SocketPackage();

        package.FuncCallback = callback;
        package.UserData     = userData;
        package.MsgId        = NetWriter.MsgId - 1;
        package.ActionId     = actionId;
        package.HasLoading   = bShowLoading;
        package.SendTime     = DateTime.Now;
        NetWriter.resetData();

        if (bShowLoading)
        {
            RequestDelegate(Status.eStartRequest);
        }
        mSocket.Request(data, package);
    }
    /// <summary>
    /// rebuild socket send hearbeat package
    /// </summary>
    public SocketPackage ReBuildHearbeat()
    {
        var writer = NetWriter.Instance;

        SprotoType.package headPack = new SprotoType.package()
        {
            protoId   = 2,
            session   = NetWriter.MsgId,
            errorcode = 0,
        };
        Sproto.SprotoPack pack      = new Sproto.SprotoPack();
        byte[]            headBytes = headPack.encode();
        writer.SetHeadBuffer(headBytes);
        writer.SetBodyData(new byte[0]);
        var data = writer.PostData();

        NetWriter.resetData();
        _hearbeatPackage = data;
        SocketPackage package = new SocketPackage();

        package.MsgId      = (int)headPack.session;
        package.ActionId   = 2;
        package.Action     = ActionFactory.Create(package.ActionId);
        package.SendTime   = DateTime.Now;
        package.HasLoading = false;
        return(package);
    }
Exemple #9
0
    public override void OnUpdate()
    {
        base.OnUpdate();

        if (mSocket != null)
        {
            mSocket.ProcessTimeOut();
            if (mSocket != null)
            {
                SocketPackage data = mSocket.Dequeue();
                if (data != null)
                {
                    OnSocketRespond(data);
                }
            }
            if (mSocket != null)
            {
                SocketPackage data = mSocket.DequeuePush();
                if (data != null)
                {
                    OnPushCallback(data);
                }
            }
        }
    }
Exemple #10
0
    /// <summary>
    /// parse input data
    /// </summary>
    /// <param name="gameAction"></param>
    /// <param name="actionParam"></param>
    /// <param name="formater"></param>
    /// <param name="bShowLoading"></param>
    private void SocketRequest(GameAction gameAction, ActionParam actionParam, IHeadFormater formater, bool bShowLoading)
    {
        if (mSocket == null)
        {
            string   strUrl = NetWriter.GetUrl();
            string[] arr    = strUrl.Split(new char[] { ':' });
            int      nPort  = int.Parse(arr[1]);
            mSocket = new SocketConnect(arr[0], nPort, formater);
        }
        gameAction.Head.MsgId = NetWriter.MsgId - 1;

        SocketPackage package = new SocketPackage();

        package.MsgId      = gameAction.Head.MsgId;
        package.ActionId   = gameAction.ActionId;
        package.Action     = gameAction;
        package.HasLoading = bShowLoading;
        package.SendTime   = DateTime.Now;
        byte[] data = gameAction.Send(actionParam);
        NetWriter.resetData();
        if (bShowLoading)
        {
            RequestDelegate(Status.eStartRequest);
        }
        mSocket.Send(data, package);
    }
Exemple #11
0
    /// <summary>
    /// Socket消息发送
    /// </summary>
    /// <param name="gameAction">消息id</param>
    /// <param name="boby">内容</param>
    /// <param name="formater">解析协议对象</param>
    /// <param name="bShowLoading">是否显示loading界面</param>
    private void SocketRequest(GameAction gameAction, byte [] boby, IHeadFormater formater, bool bShowLoading)
    {
        if (mSocket == null)
        {
            Debug.LogError("与服务器断开连接,由于服务器无响应");
            Close();
            QueueEvent(EventDef.ServerColsed);
            return;
            //string strUrl = NetWriter.GetUrl();
            //string[] arr = strUrl.Split(new char[] { ':' });
            //int nPort = int.Parse(arr[1]);
            //mSocket = new SocketConnect(arr[0], nPort, formater);
        }
        gameAction.Head.MsgId = NetWriter.MsgId;

        SocketPackage package = new SocketPackage();

        package.MsgId      = (int)gameAction.Head.MsgId;
        package.ActionId   = (int)gameAction.ActionId;
        package.Action     = gameAction;
        package.HasLoading = bShowLoading;
        package.SendTime   = DateTime.Now;
        byte[] data = gameAction.Send(boby);
        NetWriter.resetData();
        if (bShowLoading)
        {
            RequestDelegate(Status.eStartRequest);
        }
        mSocket.Send(data, package);
    }
Exemple #12
0
 private void ReceiveBodyData(IAsyncResult ar)
 {
     try
     {
         SocketPackage package = (SocketPackage)ar.AsyncState;
         int           num     = socketTcp.EndReceive(ar);
         if (num > 0)
         {
             package.bodyIndex += num;
             if (package.bodyIndex < package.bodyLength)
             {
                 socketTcp.BeginReceive(package.bodyBuffer, package.bodyIndex, package.bodyLength - package.bodyIndex, SocketFlags.None, ReceiveBodyData, package);
             }
             else
             {
                 string msg = Encoding.UTF8.GetString(package.bodyBuffer);
                 OnReciveMsg(msg);
                 package.ResetData();
                 socketTcp.BeginReceive(package.headBuffer, 0, package.headLength, SocketFlags.None, ReceiveHeadData, package);
             }
         }
         else
         {
             OnDisConnected();
             Clear();
         }
     }
     catch (Exception ex)
     {
         SocketTools.LogMsg("RcvBodyError:" + ex.Message, LogLevel.Error);
     }
 }
Exemple #13
0
 private void ReceiveBodyData(IAsyncResult ar)
 {
     try
     {
         SocketPackage package = (SocketPackage)ar.AsyncState;
         int           num     = socketTcp.EndReceive(ar);
         if (num > 0)
         {
             package.bodyIndex += num;
             if (package.bodyIndex < package.bodyLength)
             {
                 socketTcp.BeginReceive(package.bodyBuffer, package.bodyIndex, package.bodyLength - package.bodyIndex, SocketFlags.None, ReceiveBodyData, package);
             }
             else
             {
                 //string msg = Encoding.UTF8.GetString(package.bodyBuffer);
                 AddMsgQueue(package.bodyBuffer);
                 package.ResetData();
                 socketTcp.BeginReceive(package.headBuffer, 0, package.headLength, SocketFlags.None, ReceiveHeadData, package);
             }
         }
         else
         {
             Clear();
         }
     }
     catch (Exception ex)
     {
         Debug.LogError("RcvBodyError:" + ex.Message);
     }
 }
Exemple #14
0
    public void OnPushCallback(SocketPackage package)
    {
        try
        {
            if (package == null) return;
            //do Heartbeat package
            if (package.ActionId == 1) return;

            GameAction gameAction = ActionFactory.Create(package.ActionId);
            if (gameAction == null)
            {
                throw new ArgumentException(string.Format("Not found {0} of GameAction object.", package.ActionId));
            }
            NetReader reader = package.Reader;
            bool result = true;
            if (CommonCallback != null)
            {
                result = CommonCallback(reader);
            }

            if (result && gameAction.TryDecodePackage(reader))
            {
                ActionResult actionResult = gameAction.GetResponseData();
                gameAction.OnCallback(actionResult);
            }
            else
            {
                Debug.Log("Decode package fail.");
            }
        }
        catch (Exception ex)
        {
            Debug.LogException(ex);
        }
    }
Exemple #15
0
 public static void AddPushActionID(int actionID, INetCallback callback)
 {
     RemovePushActionID(actionID);
     SocketPackage package = new SocketPackage();
     package.ActionId = actionID;
     package.FuncCallback = callback;
     pushActionList.Add(package);
 }
Exemple #16
0
 static public void PushActionPool(int actionId, GameAction action)
 {
     RemoveActionPool(actionId);
     SocketPackage package = new SocketPackage();
     package.ActionId = actionId;
     package.Action = action;
     ActionPools.Add(package);
 }
Exemple #17
0
    static public void AddPushActionID(int actionID, INetCallback callback)
    {
        RemovePushActionID(actionID);
        SocketPackage package = new SocketPackage();

        package.ActionId     = actionID;
        package.FuncCallback = callback;
        pushActionList.Add(package);
    }
    static public void PushActionPool(int actionId, GameAction action)
    {
        RemoveActionPool(actionId);
        SocketPackage package = new SocketPackage();

        package.ActionId = actionId;
        package.Action   = action;
        ActionPools.Add(package);
    }
Exemple #19
0
    public void Login(string username, string password)
    {
        SocketPackage package = new SocketPackage()
        {
            identifier = "login", packet = username, token = password
        };

        ws.SendText(JsonConvert.SerializeObject(package));
    }
Exemple #20
0
        static void Main(string[] args)
        {
            int PortNumber = int.Parse(ConfigurationSettings.AppSettings["NumeroPorta"].ToString());

            SocketPackage SockPkg = new SocketPackage();

            SockPkg.StartListen(PortNumber);

            Console.Read();
        }
Exemple #21
0
        private void MonitorClient()
        {
            long lastRun = DateTime.UtcNow.Ticks;

            while (_bKeepRunning)
            {
                try
                {
                    TimeSpan ts = new TimeSpan(DateTime.UtcNow.Ticks - lastRun);
                    if (ts.TotalMilliseconds > 30000)
                    {
                        lastRun = DateTime.UtcNow.Ticks;

                        string sonda = GerarSonda();

                        List <int> toDelete = new List <int>();
                        foreach (ClientHandlerState state in dctClientes.Values)
                        {
                            try
                            {
                                logger.Info("Enviando sonda para cliente " + state.ClientNumber + "[" + state.ClientSocket.RemoteEndPoint.ToString() + "]");
                                SocketPackage.SendData(sonda, state.ClientSocket);
                                state.TentativasSonda = 0;
                            }
                            catch (Exception ex)
                            {
                                logger.Error("Erro ao enviar sonda para [" + state.ClientNumber + "]");
                                state.TentativasSonda++;

                                if (state.TentativasSonda > 5)
                                {
                                    logger.Error("Erro ao enviar sonda para [" + state.ClientNumber + "] removendo cliente");
                                    toDelete.Add(state.ClientNumber);
                                }
                            }
                        }

                        if (toDelete.Count > 0)
                        {
                            foreach (int clientNumber in toDelete)
                            {
                                dctClientes.Remove(clientNumber);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.Error("MonitorClient(): " + ex.Message, ex);
                }

                Thread.Sleep(100);
            }
        }
Exemple #22
0
    void Send(string identifier, string data)
    {
        SocketPackage package = new SocketPackage {
            identifier = identifier,
            packet     = data,
            token      = token
        };
        string json = JsonUtility.ToJson(package);

        ws.SendText(json);
    }
Exemple #23
0
 void Update()
 {
     if (mSocket != null)
     {
         mSocket.ProcessTimeOut();
         SocketPackage data = mSocket.Dequeue();
         if (data != null)
         {
             OnSocketRespond(data);
         }
     }
 }
        private void Connection_OnSocketConnectionReceivedSuccess(SocketConnection connection, byte[] data)
        {
            if (data.Length > 0)
            {
                SocketPackage package = SocketPackage.Unpackage(data);

                Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
                {
                    switch (package.Action)
                    {
                    /// =============================
                    /// 身分驗證成功
                    /// =============================
                    case SocketPackage.EnumAction.AuthenticationResponse:
                        _server.Connections.Where(x => x == connection).First().User = JsonConvert.DeserializeObject <User>(package.Data);
                        ShowMessage(String.Format("user {0} was signed in", JsonConvert.DeserializeObject <User>(package.Data).Account));
                        ShowInformation();
                        break;

                    /// =============================
                    /// 使用者登出
                    /// =============================
                    case SocketPackage.EnumAction.ClientSignout:
                        _server.Connections.RemoveAll(x => x.User.Account == package.Data);
                        ShowMessage(String.Format("user {0} was signed out", package.Data));
                        ShowInformation();
                        break;

                    /// =============================
                    /// 傳遞訊息
                    /// =============================
                    case SocketPackage.EnumAction.ClientSendMessage:
                        Message message         = JsonConvert.DeserializeObject <Message>(package.Data);
                        SocketConnection target = _server.Connections.Where(x => x.User.Account == message.To.Account).FirstOrDefault();
                        if (target != null)
                        {
                            target.Send(new SocketPackage()
                            {
                                Action = SocketPackage.EnumAction.ClientReciveMessage,
                                Data   = package.Data
                            });
                            ShowMessage(String.Format("user {0} → user {1} (success): {2}", message.From.Name, message.To.Name, message.Content));
                        }
                        else
                        {
                            ShowMessage(String.Format("user {0} → user {1} (failed): {2}", message.From.Name, message.To.Name, message.Content));
                        }
                        break;
                    }
                }));
            }
        }
Exemple #25
0
 private void StartReceiveMsg(Socket socket, Action closeCallBack = null)
 {
     try
     {
         this.closeCallBack = closeCallBack;
         SocketPackage pEPkg = new SocketPackage();
         socket.BeginReceive(pEPkg.headBuffer, 0, pEPkg.headLength, SocketFlags.None, ReceiveHeadData, pEPkg);
     }
     catch (Exception ex)
     {
         Debug.LogError("StartRcvData:" + ex.Message);
     }
 }
Exemple #26
0
        public void Start()
        {
            _bKeepRunning = true;
            sockServer    = new SocketPackage();

            sockServer.OnClientConnected    += new ClientConnectedHandler(sockServer_OnClientConnected);
            sockServer.OnClientDisconnected += new ClientDisconnectedHandler(sockServer_OnClientDisconnected);
            sockServer.StartListen(ListenPortNumber);

            myThread      = new Thread(new ThreadStart(MonitorClient));
            myThread.Name = myThreadName;
            myThread.Start();
        }
 private void SendHeartbeatPackage(object state)
 {
     try
     {
         SocketPackage pack = ReBuildHearbeat();
         Send(_hearbeatPackage, pack);
     }
     catch (Exception ex)
     {
         Debug.LogError("发送心跳出现异常");
         Debug.LogException(ex);
     }
 }
        private void _server_OnSocketServerAcceptedSuccess(SocketServer sender, Socket accept)
        {
            SocketConnection connection = new SocketConnection(accept);

            connection.OnSocketConnectionReceivedSuccess += Connection_OnSocketConnectionReceivedSuccess;
            _server.Connections.Add(connection);

            ShowMessage(String.Format("{0} try to connect... ...", ((IPEndPoint)accept.RemoteEndPoint).Address.ToString()));
            accept.Send(SocketPackage.Stream(new SocketPackage()
            {
                Action = SocketPackage.EnumAction.AuthenticationRequest
            }));
        }
Exemple #29
0
 protected virtual void OnPushCallback(SocketPackage package)
 {
     try
     {
         NetPushCallback handler = PushCallback;
         if (handler != null)
         {
             handler.BeginInvoke(package, null, null);
         }
     }
     catch (Exception)
     {
     }
 }
Exemple #30
0
 static int OnPushCallback(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 2);
         Net           obj  = (Net)ToLua.CheckObject <Net>(L, 1);
         SocketPackage arg0 = (SocketPackage)ToLua.CheckObject <SocketPackage>(L, 2);
         obj.OnPushCallback(arg0);
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Exemple #31
0
 public void StartRcvData(Socket socket, Action closeCallBack)
 {
     try
     {
         this.socketTcp     = socket;
         this.closeCallBack = closeCallBack;
         OnConnected();
         SocketPackage pEPkg = new SocketPackage();
         socket.BeginReceive(pEPkg.headBuffer, 0, pEPkg.headLength, SocketFlags.None, ReceiveHeadData, pEPkg);
     }
     catch (Exception ex)
     {
         SocketTools.LogMsg("StartRcvData:" + ex.Message, LogLevel.Error);
     }
 }
        protected override void queueProcessor()
        {
            logger.Info("Iniciando thread para otimizar eventos");

            thOtimizadorEventos      = new Thread(new ThreadStart(otimizadorEventos));
            thOtimizadorEventos.Name = "thOtimizadorEventos-";
            thOtimizadorEventos.Start();

            logger.Info("Iniciando processamento da fila de envio streamer de LOA");
            long lastLogTicks = 0;

            while (bKeepRunning)
            {
                try
                {
                    string msglof = null;
                    lock (objLockSnapshot)
                    {
                        if (queueToStreamer.TryDequeue(out msglof))
                        {
                            if (!String.IsNullOrEmpty(msglof))
                            {
                                SocketPackage.SendData(msglof, ClientSocket);
                            }

                            if (MDSUtils.shouldLog(lastLogTicks))
                            {
                                lastLogTicks = DateTime.UtcNow.Ticks;
                                logger.Info("Mensagens na fila: " + queueToStreamer.Count);
                            }
                            continue;
                        }
                    }

                    lock (syncQueueToStreamer)
                    {
                        Monitor.Wait(syncQueueToStreamer, 50);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error("queueProcessor(): " + ex.Message, ex);
                }
            }

            logger.Info("Finalizando processamento da fila de envio streamer de LOA");
        }
Exemple #33
0
    public void OnPushCallback(SocketPackage package)
    {
        try
        {
            if (package == null)
            {
                return;
            }
            //do Heartbeat package
            if (package.ActionId == 1)
            {
                return;
            }

            GameAction gameAction = ActionFactory.Create(package.ActionId);
            if (gameAction == null)
            {
                throw new ArgumentException(string.Format("Not found {0} of GameAction object.", package.ActionId));
            }
            NetReader reader = package.Reader;
            bool      result = true;
            if (CommonCallback != null)
            {
                result = CommonCallback(reader);
            }

            if (result && gameAction.TryDecodePackage(reader))
            {
                ActionResult actionResult = gameAction.GetResponseData();
                gameAction.OnCallback(actionResult);
                GameAction.OnActionCallback(gameAction.ActionId, actionResult);
            }
            else
            {
                Debug.Log("Decode package fail.");
            }
        }
        catch (Exception ex)
        {
            Debug.LogException(ex);
        }
    }
 public WebRequestHandler(ContentPackage contentPackage, SocketPackage socketPackage)
 {
     this.contentPackage = contentPackage;
     this.socketPackage = socketPackage;
 }
Exemple #35
0
    public void Request(byte[] data, SocketPackage package)
    {
        if (data == null)
        {
            return;
        }
        lock (sendList)
        {
            sendList.Add(package);
        }

        try
        {
            bool bRet = Send(data);
            UnityEngine.Debug.Log("Socket Request Id:" + package.ActionId.ToString() + " " + package.MsgId.ToString() + "send:" + bRet.ToString());
        }
        catch (System.Exception ex)
        {
            UnityEngine.Debug.Log("Request error" + ex.ToString());
            package.ErrorCode = (int)ErrorCode.eConnectError;
            package.ErrorMsg = ex.ToString();
            lock (receiveQueue)
            {
                receiveQueue.Enqueue(package);
            }
            lock (sendList)
            {
                sendList.Remove(package);
            }
        }
    }
Exemple #36
0
 protected virtual void OnPushCallback(SocketPackage package)
 {
     try
     {
         NetPushCallback handler = PushCallback;
         if (handler != null) handler.BeginInvoke(package, null, null);
     }
     catch (Exception)
     {
     }
 }
Exemple #37
0
    public void Send(byte[] data, SocketPackage package)
    {
        if (data == null)
        {
            return;
        }
        lock (_sendList)
        {
            _sendList.Add(package);
        }

        try
        {
            PostSend(data);
            //UnityEngine.Debug.Log("Socket send actionId:" + package.ActionId + ", msgId:" + package.MsgId + ", send result:" + bRet);
        }
        catch (Exception ex)
        {
            UnityEngine.Debug.Log("Socket send actionId: " + package.ActionId + " error" + ex);
            package.ErrorCode = (int)ErrorCode.ConnectError;
            package.ErrorMsg = ex.ToString();
            lock (_receiveQueue)
            {
                _receiveQueue.Enqueue(package);
            }
            lock (_sendList)
            {
                _sendList.Remove(package);
            }
        }
    }
Exemple #38
0
    private void CheckReceive()
    {
        while (true)
        {
            if (_socket == null) return;
            try
            {
                if (_socket.Poll(5, SelectMode.SelectRead))
                {
                    if (_socket.Available == 0)
                    {
                        Debug.Log("Close Socket");
                        Close();
                        break;
                    }
                    byte[] prefix = new byte[4];
                    int recnum = _socket.Receive(prefix);

                    if (recnum == 4)
                    {
                        int datalen = BitConverter.ToInt32(prefix, 0);
                        byte[] data = new byte[datalen];
                        int startIndex = 0;
                        recnum = 0;
                        do
                        {
                            int rev = _socket.Receive(data, startIndex, datalen - recnum, SocketFlags.None);
                            recnum += rev;
                            startIndex += rev;
                        } while (recnum != datalen);
                        //判断流是否有Gzip压缩
                        if (data[0] == 0x1f && data[1] == 0x8b && data[2] == 0x08 && data[3] == 0x00)
                        {
                            data = NetReader.Decompression(data);
                        }

                        NetReader reader = new NetReader(_formater);
                        reader.pushNetStream(data, NetworkType.Socket, NetWriter.ResponseContentType);
                        SocketPackage findPackage = null;

                        Debug.Log("Socket receive ok, revLen:" + recnum
                            + ", actionId:" + reader.ActionId
                            + ", msgId:" + reader.RmId
                            + ", error:" + reader.StatusCode + reader.Description
                            + ", packLen:" + reader.Buffer.Length);
                        lock (_sendList)
                        {
                            //find pack in send queue.
                            foreach (SocketPackage package in _sendList)
                            {
                                if (package.MsgId == reader.RmId)
                                {
                                    package.Reader = reader;
                                    package.ErrorCode = reader.StatusCode;
                                    package.ErrorMsg = reader.Description;
                                    findPackage = package;
                                    break;
                                }

                            }
                        }
                        if (findPackage == null)
                        {
                            lock (_receiveQueue)
                            {
                                //find pack in receive queue.
                                foreach (SocketPackage package in ActionPools)
                                {
                                    if (package.ActionId == reader.ActionId)
                                    {
                                        package.Reader = reader;
                                        package.ErrorCode = reader.StatusCode;
                                        package.ErrorMsg = reader.Description;
                                        findPackage = package;
                                        break;
                                    }
                                }
                            }
                        }
                        if (findPackage != null)
                        {
                            lock (_receiveQueue)
                            {
                                _receiveQueue.Enqueue(findPackage);
                            }
                            lock (_sendList)
                            {
                                _sendList.Remove(findPackage);
                            }
                        }
                        else
                        {
                            //server push pack.
                            SocketPackage package = new SocketPackage();
                            package.MsgId = reader.RmId;
                            package.ActionId = reader.ActionId;
                            package.ErrorCode = reader.StatusCode;
                            package.ErrorMsg = reader.Description;
                            package.Reader = reader;

                            lock (_pushQueue)
                            {
                                _pushQueue.Enqueue(package);
                            }
                        }

                    }

                }
                else if (_socket.Poll(5, SelectMode.SelectError))
                {
                    Close();
                    UnityEngine.Debug.Log("SelectError Close Socket");
                    break;

                }
            }
            catch (Exception ex)
            {
                UnityEngine.Debug.Log("catch" + ex.ToString());

            }

            Thread.Sleep(5);

        }

    }
Exemple #39
0
    /// <summary>
    /// socket respond
    /// </summary>
    /// <param name="package"></param>
    /// <param name="userdata"></param>
    public void OnSocketRespond(SocketPackage package)
    {
        if (package.HasLoading)
        {
            RequestDelegate(Status.eEndRequest);
        }
        if (package.ErrorCode != 0)
        {
            if (package.ErrorCode == -2)
            {
                OnNetTimeOut(package.ActionId);
            }
            else
            {
                OnNetError(package.ActionId, package.ErrorMsg);
            }

        }
        else
        {
            ServerResponse.ResponseData data = null;
            NetReader reader = package.Reader;
            bool bRet = true;

            if (CommonCallback != null)
            {
                bRet = CommonCallback(reader);
            }

            if (bRet)
            {
                data = ServerResponse.Instance.GetData(reader);
                if (package.FuncCallback != null)
                {
                    ProcessBodyData(data, package.UserData, package.FuncCallback);
                }
                else
                {
                    Debug.Log("poll message ");
                }

            }
        }
    }
Exemple #40
0
    /// <summary>
    /// parse input data
    /// </summary>
    /// <param name="gameAction"></param>
    /// <param name="userData"></param>
    /// <param name="formater"></param>
    /// <param name="bShowLoading"></param>
    private void SocketRequest(GameAction gameAction, object userData, IHeadFormater formater, bool bShowLoading)
    {
        if (mSocket == null)
        {
            string strUrl = NetWriter.GetUrl();
            string[] arr = strUrl.Split(new char[] { ':' });
            int nPort = int.Parse(arr[1]);
            mSocket = new SocketConnect(arr[0], nPort, formater);
        }
        gameAction.Head.MsgId = NetWriter.MsgId - 1;

        SocketPackage package = new SocketPackage();
        package.UserData = userData;
        package.MsgId = gameAction.Head.MsgId;
        package.ActionId = gameAction.ActionId;
        package.Action = gameAction;
        package.HasLoading = bShowLoading;
        package.SendTime = DateTime.Now;
        byte[] data = gameAction.Send(userData);
        NetWriter.resetData();
        if (bShowLoading)
        {
            RequestDelegate(Status.eStartRequest);
        }
        mSocket.Send(data, package);
    }
Exemple #41
0
    /// <summary>
    /// socket respond
    /// </summary>
    /// <param name="package"></param>
    private void OnSocketRespond(SocketPackage package)
    {
        if (package.HasLoading)
        {
            RequestDelegate(Status.eEndRequest);
        }
        if (package.ErrorCode != 0)
        {
            if (package.ErrorCode == -2)
            {
                OnNetTimeOut(package.ActionId);
            }
            else
            {
                OnNetError(package.ActionId, package.ErrorMsg);
            }

        }
        else
        {
            OnRespond(package);
        }
    }
Exemple #42
0
        /// <summary>
        /// parse input data
        /// </summary>
        /// <param name="gameAction"></param>
        /// <param name="actionParam"></param>
        /// <param name="formater"></param>
        /// <param name="bShowLoading"></param>
        private void SocketRequest(GameAction gameAction, ActionParam actionParam, IHeadFormater formater, bool bShowLoading)
        {
            if (mSocket == null)
            {
                string url = NetWriter.GetUrl();
                string[] arr = url.Split(new char[] { ':' });
                if (arr.Length != 2)
                {
                    Debug.LogError("Url is error:" + url);
                    return;
                }
                int nPort = int.Parse(arr[1]);
                mSocket = new SocketConnect(arr[0], nPort, formater);

            }
            gameAction.Head.MsgId = NetWriter.MsgId - 1;

            SocketPackage package = new SocketPackage();
            package.MsgId = gameAction.Head.MsgId;
            package.ActionId = gameAction.ActionId;
            package.Action = gameAction;
            package.HasLoading = bShowLoading;
            package.SendTime = DateTime.Now;
            byte[] data = gameAction.Send(actionParam);
            NetWriter.resetData();
            if (bShowLoading)
            {
                RequestDelegate(Status.eStartRequest);
            }
            mSocket.Send(data, package);
        }
Exemple #43
0
    /// <summary>
    /// parse input data
    /// </summary>
    /// <param name="url"></param>
    /// <param name="callback"></param>
    /// <param name="ud"></param>
    public void SocketRequest(int actionId, INetCallback callback, object userData, bool bShowLoading)
    {
        if (mSocket == null)
        {
            string strUrl = NetWriter.GetUrl();
            Debug.Log("url" + strUrl);
            string[] arr = strUrl.Split(new char[] { ':' });
            int nPort = int.Parse(arr[1]);
            mSocket = new SocketConnect(arr[0], nPort);
        }
        NetWriter writer = NetWriter.Instance;
        writer.writeInt32("actionId", actionId);
        byte[] data = NetWriter.Instance.PostData();
        SocketPackage package = new SocketPackage();
        package.FuncCallback = callback;
        package.UserData = userData;
        package.MsgId = NetWriter.MsgId - 1;
        package.ActionId = actionId;
        package.HasLoading = bShowLoading;
        package.SendTime = DateTime.Now;
        NetWriter.resetData();

        if (bShowLoading)
        {
            RequestDelegate(Status.eStartRequest);
        }
        mSocket.Request(data, package);
    }
 //todo: remove
 public static void AppendTo(SocketPackage socketPackage)
 {
     //throw new NotImplementedException();
 }