public void Initialize(string serverIP, int serverPort)
        {
            if (_initialized)
            {
                JLog.Error("JClientSocketManager initialized aready !", JGame.Log.JLogCategory.Network);
                return;
            }
            JNetworkServerInfo.ServerIP   = serverIP;
            JNetworkServerInfo.ServerPort = serverPort;
            IPAddress  serverAdress = IPAddress.Parse(serverIP);
            IPEndPoint serverEdp    = new IPEndPoint(serverAdress, serverPort);

            JClientSocket.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            JNetworkInteractiveData.ReceivedData = new JNetworkDataQueue();
            JNetworkInteractiveData.SendData     = new JNetworkDataQueue();

            try
            {
                JClientSocket.socket.Connect(serverEdp);
                JLog.Info("Connect to server success.", JGame.Log.JLogCategory.Network);

                JClientDataSenderThread.Initialize();
                JClientDataReceiverThread.Initialize();
            }
            catch (Exception e) {
                JLog.Error(e.Message, JGame.Log.JLogCategory.Network);
                return;
            }
        }
Esempio n. 2
0
 private bool CreateRole(JMySqlAccess mysql, string account, string roleName, int roleType, ref string roleId, ref int ErrorType)
 {
     try
     {
         string resultMssage = "";
         bool   inserResult  = mysql.DoSql(
             string.Format("INSERT into  {0}  ( role_name, user_account, role_type, scene_id)  VALUES( '{1}' , '{2}' , {3} ,  {4} );",
                           JDBUtil.TableName_Server_RoleInfo,
                           roleName,
                           account,
                           roleType,
                           JDBUtil.TableValue_SenceID_Default), ref resultMssage);
         JLog.Info("resultMssage");
         if (inserResult)
         {
             ErrorType = (int)JCreateRoleRetObject.CreateRoleResultType.successed;
             JLog.Debug("Create role success, account: " + account + " roleName:" + roleName + " roleType:" + roleType);
             return(true);
         }
         else
         {
             ErrorType = (int)JCreateRoleRetObject.CreateRoleResultType.failed;
             JLog.Debug("Create role falied, account: " + account + " roleName:" + roleName + " roleType:" + roleType);
             return(false);
         }
     }
     catch (Exception e) {
         JLog.Error(e.Message);
         ErrorType = (int)JCreateRoleRetObject.CreateRoleResultType.failed;
         return(false);
     }
 }
Esempio n. 3
0
            public static void Logic()
            {
                //根据状态调用processer处理
                //local
                List <JPacketType> addedLocalData = JLocalDataHelper.takeData();

                if (addedLocalData.Count > 0)
                {
                    JLog.Info("JLogic.Logic find local data, count : " + addedLocalData.Count.ToString(), JGame.Log.JLogCategory.Network);
                    foreach (JPacketType data in addedLocalData)
                    {
                        ProcessLocalData(data);
                    }
                }
                //network
                List <JNetworkData> receivedData = JNetworkDataOperator.TakeReceivedData();

                if (receivedData.Count > 0)
                {
                    JLog.Info("JLogic.Logic find network data, count : " + receivedData.Count.ToString(), JGame.Log.JLogCategory.Network);
                    DeSerialize(receivedData);
                    foreach (JNetworkData data in receivedData)
                    {
                        ProcessNetworkData(data);
                    }
                }
            }
Esempio n. 4
0
    public void StartServer()
    {
        if (null == ServerIP)
        {
            Debug.Log("ServerIP is null");
            return;
        }
        if (null == ServerPort)
        {
            Debug.Log("ServerPort is null");
            return;
        }

        JLog.Info("Server IP:" + ServerIP.text + "   ServerPort:" + ServerPort.text);
        JGameManager.SingleInstance.initialize(true, ServerIP.text, int.Parse(ServerPort.text));
        ServerActive = true;
        JLog.Info("initialize finished");

        /*try
         * {
         *      ServerLogic = new Thread (Logic);
         *      ServerLogic.Start ();
         *      JLog.Info("ServerManager.StartServer logic thread start success.");
         * }
         * catch (Exception e) {
         *      JLog.Error ("ServerManager.StartServer error message:"+e.Message);
         * }*/
    }
Esempio n. 5
0
    // Use this for sign in
    public void ShowRegisterRet(JObjAccountRegisterRet.AccountRegisterResultType type)
    {
        JLog.Info("Register result:" + type.ToString(), JLogCategory.Common);

        /*switch (type) {
         * case JObjAccountRegisterRet.AccountRegisterResultType.failed:
         *      UnityEditor.EditorUtility.DisplayDialog("注册", "注册失败!", "确认");
         *      break;
         * case JObjAccountRegisterRet.AccountRegisterResultType.accountNotAllowed:
         *      UnityEditor.EditorUtility.DisplayDialog("注册", "账号不合法!", "确认");
         *      break;
         * case JObjAccountRegisterRet.AccountRegisterResultType.accountRepeated:
         *      UnityEditor.EditorUtility.DisplayDialog("注册", "账号已被占用!", "确认");
         *      break;
         * case JObjAccountRegisterRet.AccountRegisterResultType.codeNotAllowed:
         *      UnityEditor.EditorUtility.DisplayDialog("注册", "密码不合法!", "确认");
         *      break;
         * case JObjAccountRegisterRet.AccountRegisterResultType.codeIsTooSimple:
         *      UnityEditor.EditorUtility.DisplayDialog("注册", "密码设置太过简单!", "确认");
         *      break;
         * case JObjAccountRegisterRet.AccountRegisterResultType.emailIsRegistered:
         *      UnityEditor.EditorUtility.DisplayDialog("注册", "邮箱已被占用", "确认");
         *      break;
         * case JObjAccountRegisterRet.AccountRegisterResultType.successed:
         *      UnityEditor.EditorUtility.DisplayDialog("注册", "注册成功!", "确认");
         *      break;
         * }*/
    }
        public void run(IDataSet dataSet)
        {
            IStreamObj obj = dataSet.getData(JObjectType.create_role_ret);

            if (null == obj || null == (obj as JCreateRoleRetObject))
            {
                JLog.Error("JProcesserCreateRoleRet : obj is empty!");
            }

            if ((obj as JCreateRoleRetObject).Result != JCreateRoleRetObject.CreateRoleResultType.successed)
            {
                JLog.Info("Received JCreateRoleRetObject create failed:!" + (obj as JCreateRoleRetObject).Result.GetDescription());
            }
            //todo:...remind to regist
            else if (null != createRole)
            {
                IStreamObj createRoleObjTemp = JLogicUserData.getLocalData().getData(JObjectType.create_role);
                if (null == createRoleObjTemp)
                {
                    return;
                }
                JCreateRoleReqObject createRoleObj = createRoleObjTemp as JCreateRoleReqObject;
                if (null == createRoleObj)
                {
                    return;
                }
                createRole(createRoleObj.RoleName, createRoleObj.RoleType);
            }
        }
Esempio n. 7
0
        /*private byte[] KeepAliveTime
         * {
         *      get
         *      {
         *              uint dummy = 0;
         *              byte[] inOptionValues = new byte[Marshal.SizeOf(dummy) * 3];
         *              BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0);
         *              BitConverter.GetBytes((uint)5000).CopyTo(inOptionValues, Marshal.SizeOf(dummy));
         *              BitConverter.GetBytes((uint)5000).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2);
         *              return inOptionValues;
         *      }
         * }
         * private const int keepAlive = -1744830460;
         * private byte[] inValue = new byte[] { 1, 0, 0, 0, 0x20, 0x4e, 0, 0, 0xd0, 0x07, 0, 0 };
         * byte[] inValue = new byte[] { 1, 0, 0, 0, 0x10, 0x27, 0, 0, 0xe8, 0x03, 0, 0 }; // True, 10秒, 1 秒
         * JServerSocket.socket.IOControl(keepAlive, inValue, null);
         * JServerSocket.socket.IOControl(IOControlCode.KeepAliveValues, inValue, null);*/

        public void Initialize(string serverIP, int serverPort)
        {
            if (_initialized)
            {
                JLog.Error("JServerSocketManager initialized aready !", JGame.Log.JLogCategory.Network);
                return;
            }

            JLog.Info("JServerSocketManager begin to initialize :", JGame.Log.JLogCategory.Network);

            _socketHeartDelayTime         = new Dictionary <Socket, ulong> ();
            _heartbeatLocker              = new object();
            JNetworkServerInfo.ServerIP   = serverIP;
            JNetworkServerInfo.ServerPort = serverPort;
            _socketLocker = new object();
            _semaphore    = new Semaphore(0, 10000);
            JNetworkInteractiveData.ReceivedData = new JNetworkDataQueue();
            JNetworkInteractiveData.SendData     = new JNetworkDataQueue();
            IPAddress  ip_server  = IPAddress.Parse(serverIP);
            IPEndPoint server_edp = new IPEndPoint(ip_server, serverPort);

            JServerSocket.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                JServerSocket.socket.Bind(server_edp);
                JLog.Info("JServerSocketManager server socket bind to server endpoint finished.\nIP:" + serverIP + "\nPort:" + serverPort.ToString(),
                          JGame.Log.JLogCategory.Network);

                JServerSocket.socket.Listen(JTcpDefines.max_tcp_connect);
                JLog.Info("JServerSocketManager server socket begin listen", JGame.Log.JLogCategory.Network);

                _serverSendThread = new Thread(SendLoop)
                {
                    IsBackground = true
                };
                _serverSendThread.Start();

                _serverReceiveThread = new Thread(ReceiveLoop)
                {
                    IsBackground = true
                };
                _serverReceiveThread.Start();

                _serverAcceptThread = new Thread(AcceptLoop)
                {
                    IsBackground = true
                };
                _serverAcceptThread.Start();
            }
            catch (Exception e) {
                JLog.Error("JServerSocketManager initialize faield  error message: " + e.Message, JGame.Log.JLogCategory.Network);
                return;
            }

            //start heart beat check
            _headbeatTimer          = new System.Timers.Timer(1000);
            _headbeatTimer.Elapsed += heatbeatTest;
            _headbeatTimer.Start();
        }
Esempio n. 8
0
        private void AcceptLoop()
        {
            JLog.Info("JServerSocketManager server accept loop started", JGame.Log.JLogCategory.Network);

            while (true)
            {
                //JLog.Debug("AcceptLoop loop one begin ...", JGame.Log.JLogCategory.Network);

                if (_forceEnd)
                {
                    break;
                }

                try
                {
                    JLog.Debug("JServerSocketManager.AcceptLoop begin to accept", JGame.Log.JLogCategory.Network);
                    Socket currentConnectedSocket = JServerSocket.socket.Accept();
                    JLog.Debug("JServerSocketManager.AcceptLoop accept finished, to process accepted socket", JGame.Log.JLogCategory.Network);
                    if (null != currentConnectedSocket && currentConnectedSocket.Connected)
                    {
                        lock (_socketLocker)
                        {
                            if (!JConnectedClientSocket.sockets.Contains(currentConnectedSocket))
                            {
                                JConnectedClientSocket.sockets.Add(currentConnectedSocket);

                                JLog.Info("JServerSocketManager.AcceptLoop client connected :" +
                                          (currentConnectedSocket.RemoteEndPoint as IPEndPoint).Address.ToString(), JGame.Log.JLogCategory.Network);
                                _semaphore.Release();
                            }
                            else
                            {
                                JLog.Info("JServerSocketManager.AcceptLoop connected client connected again"
                                          + (currentConnectedSocket.RemoteEndPoint as IPEndPoint).Address.ToString(), JGame.Log.JLogCategory.Network);
                            }
                        }

                        lock (_heartbeatLocker)
                        {
                            if (!_socketHeartDelayTime.ContainsKey(currentConnectedSocket))
                            {
                                _socketHeartDelayTime.Add(currentConnectedSocket, 0);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    JLog.Error("JServerSocketManager accept loop error message:" + e.Message, JGame.Log.JLogCategory.Network);
                    Thread.Sleep(200);
                }

                //JLog.Debug("AcceptLoop loop one end ...", JGame.Log.JLogCategory.Network);
            }

            JLog.Info("JServerSocketManager server accept loop end.", JGame.Log.JLogCategory.Network);
        }
Esempio n. 9
0
    //登录检查
    public void ToSendRegisterData()
    {
        if (!UserCode1.text.Equals(UserCode2.text))
        {
            JLog.Info("两次密码输入不一致!");
            return;
        }

        //ToDo:验证用户输入的账号、密码、邮箱合法

        JObjAccountRegisterReq obj = new JObjAccountRegisterReq();

        obj._strAccount      = UserAccount.text;
        obj._strCode         = UserCode1.text;
        obj._strEmailAddress = UserEmail.text;
        JLocalDataHelper.addData(JPacketType.npt_accountRegister_req, obj);
    }
        public static void MainLoop()
        {
            if (null == JNetworkInteractiveData.SendData ||
                null == JNetworkInteractiveData.SendData.Data)
            {
                JLog.Error("JNetworkDataSenderThread: JNetworkInteractiveData checked empty, please check initialize", JGame.Log.JLogCategory.Network);
                return;
            }

            if (null == JClientSocket.socket)
            {
                JLog.Error("JNetworkDataSenderThread: JClientSocket.socket is null, please check initialize", JGame.Log.JLogCategory.Network);
                return;
            }

            JLog.Info("JNetworkDataSenderThread: main loop started", JGame.Log.JLogCategory.Network);

            while (true)
            {
                if (_requireEnd)
                {
                    break;
                }

                try
                {
                    List <JNetworkData> dataList = JNetworkDataOperator.TakeSendData(1000);
                    if (null == dataList)
                    {
                        continue;
                    }

                    foreach (JNetworkData data in dataList)
                    {
                        JClientSocket.socket.Send(data.Data);
                        JLog.Debug("JNetworkDataSenderThread: send one network packet", JGame.Log.JLogCategory.Network);
                    }
                }
                catch (Exception e) {
                    JLog.Error(e.Message, JGame.Log.JLogCategory.Network);
                }
            }

            JLog.Info("JNetworkDataSenderThread main loop end.", JGame.Log.JLogCategory.Network);
        }
Esempio n. 11
0
        private void SendLoop()
        {
            JLog.Info("JServerSocketManager server send loop started", JGame.Log.JLogCategory.Network);

            while (true)
            {
                if (_forceEnd)
                {
                    break;
                }
                List <JNetworkData> dataList = JNetworkDataOperator.TakeSendData(1000);
                if (null == dataList)
                {
                    continue;
                }

                foreach (JNetworkData data in dataList)
                {
                    lock (_socketLocker) {
                        foreach (Socket socket in JConnectedClientSocket.sockets)
                        {
                            if (null == socket || null == socket.RemoteEndPoint)
                            {
                                continue;
                            }

                            if (JNetworkHelper.IsSameEndpoint(data.RemoteEndPoint as IPEndPoint, socket.RemoteEndPoint as IPEndPoint))
                            {
                                try
                                {
                                    socket.Send(data.Data);
                                    JLog.Info("send one data to " + (socket.RemoteEndPoint as IPEndPoint).Address.ToString(), JGame.Log.JLogCategory.Network);
                                }
                                catch (Exception e) {
                                    JLog.Error("SendLoop error message:" + e.Message, JGame.Log.JLogCategory.Network);
                                }
                            }
                        }
                    }
                }
            }

            JLog.Info("JServerSocketManager server send loop end", JGame.Log.JLogCategory.Network);
        }
Esempio n. 12
0
        private void heatbeatTest(object sender, ElapsedEventArgs e)
        {
            if (null == _socketHeartDelayTime || _socketHeartDelayTime.Count <= 0)
            {
                return;
            }

            foreach (var time in _socketHeartDelayTime)
            {
                if (JTime.CurrentTime - time.Value > 10000)                 //10s
                {
                    lock (_heartbeatLocker)
                    {
                        _socketHeartDelayTime.Remove(time.Key);
                        JLog.Info(string.Format("JServerSocektManager.Heartbeat Client dissconnected : {0}",
                                                (time.Key.RemoteEndPoint as IPEndPoint).Address.ToString()), JGame.Log.JLogCategory.Network);
                    }
                }
            }
        }
Esempio n. 13
0
        public void run(IDataSet dataSet)
        {
            IStreamObj obj = dataSet.getData(JObjectType.sign_in_ret);

            if (null == obj || null == (obj as JObj_SignRet))
            {
                JLog.Error("JProcesserSignInGet : obj is empty!");
            }

            if ((obj as JObj_SignRet).Result == false)
            {
                JLog.Info("Received JObj_SignRet but account and code is not registed!");
            }
            //todo:...remind to regist
            else if (null != toSignIn)
            {
                JLogicUserData.setLocalData(obj);
                toSignIn();
            }
        }
        private void AcceptLoop()
        {
            JLog.Info("JServerSocketManager server accept loop started", JGame.Log.JLogCategory.Network);

            while (true)
            {
                //JLog.Debug("AcceptLoop loop one begin ...", JGame.Log.JLogCategory.Network);

                if (_forceEnd)
                {
                    break;
                }

                try
                {
                    Socket currentConnectedSocket = JServerSocket.socket.Accept();
                    if (null != currentConnectedSocket)
                    {
                        lock (_socketLocker)
                        {
                            if (!JConnectedClientSocket.sockets.Contains(currentConnectedSocket))
                            {
                                JConnectedClientSocket.sockets.Add(currentConnectedSocket);

                                JLog.Info("client connected :" + (currentConnectedSocket.RemoteEndPoint as IPEndPoint).Address.ToString(), JGame.Log.JLogCategory.Network);
                                _semaphore.Release();
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    JLog.Error("JServerSocketManager accept loop error message:" + e.Message, JGame.Log.JLogCategory.Network);
                }

                //JLog.Debug("AcceptLoop loop one end ...", JGame.Log.JLogCategory.Network);
            }

            JLog.Info("JServerSocketManager server accept loop end.", JGame.Log.JLogCategory.Network);
        }
Esempio n. 15
0
        /// <summary>
        /// Opens my sql.
        /// </summary>
        private bool OpenMySql()
        {
            string strConnectString =
                string.Format("Database={0};Data Source={1};User Id={2};Password={3}",
                              DatabaseName, Datasource, UserID, UserPassword);

            try {
                _mysql_connection = new MySqlConnection(strConnectString);
                _mysql_connection.Open();
            } catch (Exception) {
                JLog.Error("Open mysql database Exception.");
                return(false);
            }

            if (_mysql_connection.State == System.Data.ConnectionState.Open)
            {
                JLog.Info("Open mysql success.");
                return(true);
            }
            JLog.Error("Open mysql database failed.");
            return(false);
        }
            public void run(IDataSet dataSet)
            {
                IStreamObj  obj       = dataSet.getData(JObjectType.sign_in);
                JObj_SignIn signInObj = obj as JObj_SignIn;

                if (signInObj == null)
                {
                    return;
                }

                string account = signInObj._strAccount;
                string code    = signInObj._strCode;

                JLog.Info("receive npt_signin_req packet from client: account:" + account + "  code:" + code, JGame.Log.JLogCategory.Network);

                JObj_SignRet resultObj = new JObj_SignRet();

                //ToDo:if account and code is in database then
                if (account == "test" && code == "123")
                {
                    resultObj.Result = true;
                }
                else
                {
                    resultObj.Result = false;
                }

                try {
                    JNetworkDataOperator.SendData(JPacketType.npt_signin_ret, resultObj);
                    JLog.Info("send npt_signin_ret packet to client", JGame.Log.JLogCategory.Network);
                    return;
                } catch (Exception e) {
                    JLog.Debug("发送数据失败");
                    JLog.Error(e.Message);
                    return;
                }
            }
Esempio n. 17
0
    public void ShutDownServer()
    {
        if (null != ServerManager.ServerLogic && ServerManager.ServerLogic.IsAlive)
        {
            try
            {
                ServerManager.ServerLogic.Abort();
                JLog.Info("Server logic aborted");
            }
            catch (Exception e) {
                JLog.Error(e.Message);
            }
        }

        if (JGameManager.SingleInstance.ShutDown())
        {
            ServerManager.ServerActive = false;
            Debug.Log("Server shut down : finished");
        }
        else
        {
            Debug.Log("Server shut down : falied");
        }
    }
            public void run(IDataSet dataSet)
            {
                IStreamObj             obj = dataSet.getData(JObjectType.account_register);
                JObjAccountRegisterReq accountRegisterObj = obj as JObjAccountRegisterReq;

                if (accountRegisterObj == null)
                {
                    return;
                }

                JMySqlAccess mysql = new JMySqlAccess(JDBUtil.ServerDatabaseName, JDBUtil.ServerDatasource, JDBUtil.ServerUser, JDBUtil.ServerUserCode);

                if (!mysql.Open())
                {
                    return;
                }
                if (!mysql.Connected)
                {
                    return;
                }

                DataSet data = mysql.Select(string.Format(
                                                @"Select count(1) from {0} t where t.user_account = '{1}' or t.user_email = '{2}'",
                                                JDBUtil.TableName_Server_UserInfo,
                                                accountRegisterObj._strAccount,
                                                accountRegisterObj._strEmailAddress));

                bool bAreadyExisted = false;

                do
                {
                    if (null == data || null == data.Tables)
                    {
                        break;
                    }
                    if (data.Tables.Count <= 0)
                    {
                        break;
                    }
                    if (null == data.Tables[0].Rows || data.Tables[0].Rows.Count <= 0)
                    {
                        break;
                    }
                    if (int.Parse(data.Tables[0].Rows[0][0].ToString()) == 1)
                    {
                        bAreadyExisted = true;
                    }
                }while(false);

                JObjAccountRegisterRet retObj = new JObjAccountRegisterRet();

                try
                {
                    if (!bAreadyExisted)
                    {
                        string resultMssage = "";
                        bool   inserResult  = mysql.DoSql(
                            string.Format("INSERT into  {0}  ( user_account, user_code, user_email)  VALUES( '{1}' , '{2}' , '{3}' );",
                                          JDBUtil.TableName_Server_UserInfo,
                                          accountRegisterObj._strAccount,
                                          accountRegisterObj._strCode,
                                          accountRegisterObj._strEmailAddress), ref resultMssage);
                        JLog.Info("resultMssage");
                        if (inserResult)
                        {
                            retObj.Result = JObjAccountRegisterRet.AccountRegisterResultType.successed;
                            JLog.Debug("Create account success, account: " + accountRegisterObj._strAccount);
                        }
                        else
                        {
                            retObj.Result = JObjAccountRegisterRet.AccountRegisterResultType.failed;
                            JLog.Debug("Create account falied, account: " + accountRegisterObj._strAccount);
                        }
                    }
                    else
                    {
                        retObj.Result = JObjAccountRegisterRet.AccountRegisterResultType.accountRepeated;
                    }
                }
                catch (Exception e) {
                    JLog.Error(e.Message);
                }
                finally {
                    mysql.Close();
                }

                try {
                    JNetworkDataOperator.SendData(JPacketType.npt_accountRegister_ret, retObj, dataSet.EndPoint);
                    JLog.Info("send npt_accountRegister_ret packet to client", JGame.Log.JLogCategory.Network);
                    return;
                } catch (Exception e) {
                    JLog.Debug("发送数据失败");
                    JLog.Error(e.Message);
                    return;
                }
            }
Esempio n. 19
0
        public void run(IDataSet dataSet)
        {
            JCreateRoleRetObject createRoleRetObj = new JCreateRoleRetObject();

            createRoleRetObj.Result = JCreateRoleRetObject.CreateRoleResultType.failed;
            do
            {
                //check role info existed
                IStreamObj signinObj = dataSet.getData(JObjectType.sign_in_info);
                if (null == signinObj)
                {
                    createRoleRetObj.Result = JCreateRoleRetObject.CreateRoleResultType.failed;
                    JLog.Error("JProcessorCreateRole.run can not find sign in account info");
                    break;
                }
                JSignInClientInfoObject clientInfo = signinObj as JSignInClientInfoObject;
                string account = clientInfo.Info.Account;

                //process create role request
                IStreamObj           obj = dataSet.getData(JObjectType.create_role);
                JCreateRoleReqObject createRoleReqObj = obj as JCreateRoleReqObject;
                if (createRoleReqObj == null)
                {
                    createRoleRetObj.Result = JCreateRoleRetObject.CreateRoleResultType.failed;
                    break;
                }

                string roleName = createRoleReqObj.RoleName;
                int    roleType = createRoleReqObj.RoleType;

                //open data base
                JMySqlAccess mysql = new JMySqlAccess(JDBUtil.ServerDatabaseName, JDBUtil.ServerDatasource, JDBUtil.ServerUser, JDBUtil.ServerUserCode);
                try
                {
                    if (!mysql.Open())
                    {
                        break;
                    }
                    if (!mysql.Connected)
                    {
                        break;
                    }
                }
                catch (Exception e)
                {
                    JLog.Error("CheckRoleNameIsValud." + e.Message);
                }

                if (!mysql.Connected)
                {
                    mysql.Close();
                    JLog.Error("JProcessorCreateRole.run open database fialied");
                    break;
                }

                //check name is valid or not
                int nErrorType = 0;
                if (!CheckRoleNameIsValud(mysql, account, roleName, ref nErrorType))
                {
                    createRoleRetObj.Result = (JCreateRoleRetObject.CreateRoleResultType)nErrorType;
                    JLog.Info("JProcessorCreateRole.run Create role request not valid, error type:" + createRoleRetObj.Result.GetDescription());
                    mysql.Close();
                    break;
                }
                if (!CheckRoleTypeIsValud(roleType, ref nErrorType))
                {
                    createRoleRetObj.Result = (JCreateRoleRetObject.CreateRoleResultType)nErrorType;
                    JLog.Info("Create role request not valid, error type:" + createRoleRetObj.Result.GetDescription());
                    mysql.Close();
                    break;
                }

                //insert new role record to role_info table
                string roleID = "";
                if (!CreateRole(mysql, account, roleName, roleType, ref roleID, ref nErrorType))
                {
                    createRoleRetObj.Result = (JCreateRoleRetObject.CreateRoleResultType)nErrorType;
                    JLog.Info("JProcessorCreateRole.run CreateRole falied, error type:" + createRoleRetObj.Result.GetDescription());
                }
                createRoleRetObj.Result = JCreateRoleRetObject.CreateRoleResultType.successed;
                mysql.Close();
            } while (false);

            try {
                JNetworkDataOperator.SendData(JPacketType.pt_createRole_ret, createRoleRetObj, dataSet.EndPoint);
            } catch (Exception e) {
                JLog.Debug("JProcessorCreateRole 发送数据失败");
                JLog.Error("JProcessorCreateRole 发送数据失败 " + e.Message);
            }
        }
Esempio n. 20
0
            public void run(IDataSet dataSet)
            {
                IStreamObj  obj       = dataSet.getData(JObjectType.sign_in);
                JObj_SignIn signInObj = obj as JObj_SignIn;

                if (signInObj == null)
                {
                    return;
                }

                string account = signInObj._strAccount;
                string code    = signInObj._strCode;

                JLog.Info("JProcesserSignInServer.run receive npt_signin_req packet from client: account:" + account + "  code:" + code, JGame.Log.JLogCategory.Network);

                JObj_SignRet resultObj = new JObj_SignRet();
                JMySqlAccess sqlite    = new JMySqlAccess("mysql", "127.0.0.1", "root", "684268");

                if (!sqlite.Open())
                {
                    return;
                }
                if (!sqlite.Connected)
                {
                    return;
                }

                DataSet data = sqlite.Select(string.Format(
                                                 @"Select * from user_info t where t.user_account = '{0}' and t.user_code = '{1}'",
                                                 signInObj._strAccount,
                                                 signInObj._strCode));

                bool bSuccess = false;

                do
                {
                    if (null == data || null == data.Tables)
                    {
                        break;
                    }
                    if (data.Tables.Count <= 0)
                    {
                        break;
                    }
                    if (null == data.Tables[0].Rows || data.Tables[0].Rows.Count <= 0)
                    {
                        break;
                    }
                    if (data.Tables[0].Rows.Count > 0)
                    {
                        bSuccess = true;
                    }
                }while(false);
                resultObj.Result = bSuccess;

                string[] items      = new string[] { "role_name", "role_type", "role_level", "x", "y", "z", "x_rotation", "y_rotation", "z_rotation", "user_account" };
                string[] where_cols = new string[] { "user_account" };
                string[] operation  = new string[] { "=" };
                string[] values     = new string[] { signInObj._strAccount };

                string  strAccount = null;
                DataSet roleInfo   = sqlite.Select("role_info", items, where_cols, operation, values);

                do
                {
                    if (null == roleInfo || null == roleInfo.Tables)
                    {
                        break;
                    }
                    if (roleInfo.Tables.Count <= 0)
                    {
                        break;
                    }
                    if (null == roleInfo.Tables[0].Rows || roleInfo.Tables[0].Rows.Count <= 0)
                    {
                        break;
                    }

                    try
                    {
                        if (roleInfo.Tables [0].Rows.Count > 0)
                        {
                            resultObj.RolesInfo = new System.Collections.Generic.List <JObjRoleInfo> ();
                            foreach (DataRow dataRow in roleInfo.Tables[0].Rows)
                            {
                                JObjRoleInfo role = new JObjRoleInfo();
                                role.roleName  = dataRow [0].ToString();
                                role.roleType  = int.Parse(dataRow [1].ToString());
                                role.roleLevel = int.Parse(dataRow [2].ToString());
                                double coord;
                                if (double.TryParse(dataRow [3].ToString(), out coord))
                                {
                                    role.x = coord;
                                }
                                if (double.TryParse(dataRow [4].ToString(), out coord))
                                {
                                    role.y = coord;
                                }
                                if (double.TryParse(dataRow [5].ToString(), out coord))
                                {
                                    role.z = coord;
                                }
                                if (double.TryParse(dataRow [6].ToString(), out coord))
                                {
                                    role.rotatex = coord;
                                }
                                if (double.TryParse(dataRow [7].ToString(), out coord))
                                {
                                    role.rotatey = coord;
                                }
                                if (double.TryParse(dataRow [8].ToString(), out coord))
                                {
                                    role.rotatez = coord;
                                }
                                resultObj.RolesInfo.Add(role);
                                strAccount = dataRow[9].ToString();
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        JLog.Error("JProcesserSignInServer.run " + e.Message);
                    }
                }while(false);

                if (null != strAccount)
                {
                    //记录当前新增的登录信息到对应的dataSet
                    IStreamObj clientobj = dataSet.getData(JObjectType.sign_in_info);
                    if (null != clientobj)
                    {
                        JSignInClientInfoObject clientInfo = clientobj as JSignInClientInfoObject;
                        clientInfo.Info.Account = strAccount;
                    }
                    else
                    {
                        JSignInClientInfoObject clientInfo = new JSignInClientInfoObject();
                        clientInfo.Info.Account = strAccount;
                        clientobj = clientInfo;
                    }
                    JLog.Info("JProcesserSignInServer.run add connected client info dataset, account:" + strAccount, JGame.Log.JLogCategory.Network);
                    dataSet.setData(clientobj);
                }

                try {
                    JNetworkDataOperator.SendData(JPacketType.npt_signin_ret, resultObj, dataSet.EndPoint);
                    JLog.Info("JProcesserSignInServer.run send npt_signin_ret packet to client", JGame.Log.JLogCategory.Network);
                    return;
                } catch (Exception e) {
                    JLog.Debug("发送数据失败");
                    JLog.Error(e.Message);
                    return;
                }
            }
Esempio n. 21
0
        private void ReceiveLoop()
        {
            JLog.Info("JServerSocketManager server receive loop started", JGame.Log.JLogCategory.Network);
            List <Socket> clientScokets = new List <Socket> ();

            while (true)
            {
                if (_forceEnd)
                {
                    break;
                }

                if (_semaphore.WaitOne(1))
                {
                    _semaphore = new Semaphore(0, 10000);
                    JLog.Info("JServerSocketManager ReceiveLoop _semaphore.WaitOne(1) success", JGame.Log.JLogCategory.Network);
                    lock (_socketLocker) {
                        foreach (Socket socket in JConnectedClientSocket.sockets)
                        {
                            clientScokets.Add(socket);
                        }
                        JLog.Info("JServerSocketManager ReceiveLoop add socket to clientsockets: count : " + clientScokets.Count.ToString(), JGame.Log.JLogCategory.Network);
                    }

                    JLog.Debug("connected client sockets : " + clientScokets.Count.ToString(), JGame.Log.JLogCategory.Network);
                }
                if (clientScokets.Count == 0)
                {
                    _semaphore.WaitOne();
                    _semaphore.Release();

                    JLog.Debug("JServerSocketManager ReceiveLoop._semaphore.WaitOne success. ", JGame.Log.JLogCategory.Network);

                    continue;
                }

                //JLog.Debug ("JServerSocketManager ReceiveLoop.Socket.Select begin Socket.Select clientsocket:count :" + clientScokets.Count.ToString (), JGame.Log.JLogCategory.Network);
                Socket.Select(clientScokets, null, null, 10000);
                if (clientScokets.Count > 0)
                {
                    JLog.Debug("JServerSocketManager ReceiveLoop.Socket.Select selected clientsockets: count : " + clientScokets.Count.ToString(), JGame.Log.JLogCategory.Network);
                }

                List <Socket> disconnectedSockets = new List <Socket>();
                foreach (Socket socket in clientScokets)
                {
                    /*if (socket.Available <= 0)
                     *      continue;*/

                    //如果接收到了新的消息就重置包时间
                    lock (_heartbeatLocker)
                    {
                        if (_socketHeartDelayTime.ContainsKey(socket))
                        {
                            _socketHeartDelayTime [socket] = JTime.CurrentTime;
                        }
                        else
                        {
                            _socketHeartDelayTime.Add(socket, JTime.CurrentTime);
                        }
                    }

                    //receive form client socket
                    bool bReceivedSuccess = false;
                    if (socket.Connected)
                    {
                        try {
                            byte[] recBuffer = new byte[JTcpDefines.max_buffer_size];
                            JLog.Info("try to receive from socket : " + (socket.RemoteEndPoint as IPEndPoint).Address.ToString(), JGame.Log.JLogCategory.Network);
                            int recLen = socket.Receive(recBuffer);
                            if (recLen > 0)
                            {
                                JLog.Info("receive one packet from client : IP" + (socket.RemoteEndPoint as IPEndPoint).Address.ToString() + " len:" + recLen.ToString(), JGame.Log.JLogCategory.Network);
                                //save the received data
                                JNetworkDataOperator.ReceiveData(recLen, recBuffer, socket.RemoteEndPoint);

                                //add the selected socket to select sockets list
                                //clientScokets.Add(socket);

                                bReceivedSuccess = true;
                            }
                        } catch (Exception e) {
                            JLog.Error("JServerSocketManager ReceiveLoop exception reveive error message:" + e.Message, JGame.Log.JLogCategory.Network);
                        }
                    }

                    try
                    {
                        if (!bReceivedSuccess)
                        {
                            //client disconnect
                            if (socket.Connected)
                            {
                                socket.Close();
                            }
                            //record disconnected socket from list
                            disconnectedSockets.Add(socket);

                            JLog.Info("client socket disconnected : " + socket.RemoteEndPoint.ToString(), JGame.Log.JLogCategory.Network);
                        }
                    }
                    catch (Exception e) {
                        JLog.Error("JServerSocketManager ReceiveLoop exception error message1:" + e.Message, JGame.Log.JLogCategory.Network);
                    }
                }

                try
                {
                    //remove disconnected socket form list
                    if (disconnectedSockets.Count > 0)
                    {
                        lock (_socketLocker) {
                            foreach (Socket socket in disconnectedSockets)
                            {
                                JConnectedClientSocket.sockets.Remove(socket);
                                clientScokets.Remove(socket);
                            }
                        }
                    }


                    //add old sockets to client sockets
                    lock (_socketLocker) {
                        foreach (Socket socket in JConnectedClientSocket.sockets)
                        {
                            clientScokets.Add(socket);
                        }
                    }
                }
                catch (Exception e) {
                    JLog.Error("JServerSocketManager ReceiveLoop exception error message2:" + e.Message, JGame.Log.JLogCategory.Network);
                }
            }

            JLog.Info("JServerSocketManager server receive loop end.", JGame.Log.JLogCategory.Network);
        }