示例#1
0
        public void SendMsg(string endPoint, ProtocolEnum protocolId, object data)
        {
            ServerClient client = GetSClient(endPoint);

            if (client != null)
            {
                try
                {
                    client.SendMsg(protocolId, data);
                }
                catch (Exception exp)
                {
                    ServerLog.Log(string.Format("Send To :{0}, Error:{1}", endPoint, exp.Message));
                }
            }
        }
示例#2
0
        public void InitServer()
        {
            try
            {
                m_listener = new TcpListener(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12000));
                m_listener.Server.NoDelay = true;
                m_listener.Start(10);

                ServerLog.Log("Server Start OK!");
                m_listener.BeginAcceptTcpClient(new AsyncCallback(AsyncListen), m_listener);
            }
            catch (Exception exp)
            {
                Console.WriteLine("Wrong When AcceptTcp Client:{0}", exp.Message);
            }
        }
示例#3
0
        public void LoadSchema(string path)
        {
            var schema = _serviceContainer.SchemaPersistence.LoadSchema(path);

            if (schema != null)
            {
                foreach (var description in schema.CollectionsDescriptions)
                {
                    ServerLog.LogInfo($"declaring collection {description.Key}");
                    RegisterType(new RegisterTypeRequest(description.Value, schema.ShardIndex, schema.ShardCount), null);
                }

                ShardIndex = schema.ShardIndex;
                ShardCount = schema.ShardCount;
            }
        }
示例#4
0
 /// <summary>
 /// 删除某项
 /// </summary>
 /// <param name="id"></param>
 /// <returns></returns>
 public bool DeleteUserInfo(int id)
 {
     try
     {
         DBMgr.MInstance.DBSession().Delete(new DBUserInfo()
         {
             MUserId = id
         });
         return(true);
     }
     catch (Exception exp)
     {
         ServerLog.Log(string.Format("Delete Wrong:{0}", exp.Message));
         return(false);
     }
 }
示例#5
0
        static void Main(string[] args)
        {
            new NetMsgDispatch();
            new ProtocolMgr().RegAssembly(typeof(STC_UserInfo).Assembly);

            new DBMgr();
            DBMgr.MInstance.onInitDBSuccess = delegate()
            {
                ServerLog.Log("DataBase Initialize OK");
                new GameModuleMgr();
                GameModuleMgr.MInstance.AddModule(new LoginModule());
                GameModuleMgr.MInstance.AddModule(new HeartBeatModule());

                new UserMgr();
                new ServerNet();
            };
            DBMgr.MInstance.InitializeDB("127.0.0.1", 3306, "database_test", "bc", "123456");

            Console.ReadKey();
        }
示例#6
0
        public void ProcessEviction()
        {
            if (EvictionPolicy.IsEvictionRequired)
            {
                var itemsToEvict = EvictionPolicy.DoEviction();

                foreach (var item in itemsToEvict)
                {
                    InternalRemoveByPrimaryKey(item.PrimaryKey);
                }

                var requestDescription = string.Empty;

                var processedItems = itemsToEvict.Count;
                var requestType    = "EVICTION";

                ServerLog.AddEntry(new ServerLogEntry(0, requestType, requestDescription,
                                                      processedItems));
            }
        }
示例#7
0
        public static T ToObject <T>(Dictionary <string, object> dict)
        {
            object obj  = Activator.CreateInstance(typeof(T));
            var    type = typeof(T);

            var tests = type.GetFields(BindingFlags.Instance | BindingFlags.Public);

            foreach (var tmp in dict)
            {
                if (tmp.Value is DBNull)
                {
                    continue; //nothing to see here
                }
                var objField = type.GetField(tmp.Key, BindingFlags.Instance | BindingFlags.Public);

                if (objField != null)
                {
                    var objFieldType = objField.FieldType;
                    try
                    {
                        objField.SetValue(obj, Convert.ChangeType(tmp.Value, objFieldType));
                    }
                    catch (Exception e)
                    {
                        ServerLog.Debug("MySQLHelper", "Exception setting {0} to {1} in {2}, details:\n{3}", tmp.Key, tmp.Value,
                                        type.ToString(), e.ToString());
                    }
                }
                else
                {
                    ServerLog.Debug("MySQLHelper", "Cannot set {0} to {1} in type {2} as field does not exist", tmp.Key, tmp.Value,
                                    type.ToString());
                }
            }

            return((T)obj);
        }
示例#8
0
        public void LoadSchema(string path)
        {
            if (!File.Exists(path))
            {
                return;
            }

            var json = File.ReadAllText(path);

            var schema = _jsonSerializer.Deserialize <Schema>(
                new JsonTextReader(new StringReader(json)));

            if (schema != null)
            {
                foreach (var typeDescription in schema.TypeDescriptions)
                {
                    ServerLog.LogInfo($"registering type {typeDescription.FullTypeName}");
                    RegisterType(new RegisterTypeRequest(typeDescription, schema.ShardIndex, schema.ShardCount), null);
                }

                ShardIndex = schema.ShardIndex;
                ShardCount = schema.ShardCount;
            }
        }
示例#9
0
        private void ProcessTransactionRequest(TransactionRequest transactionRequest, IClient client)
        {
            // First try to acquire a write lock on all concerned data stores

            var typesToPut    = transactionRequest.ItemsToPut.Select(i => i.FullTypeName).Distinct().ToList();
            var typesToDelete = transactionRequest.ItemsToDelete.Select(i => i.FullTypeName).Distinct().ToList();
            var types         = typesToPut.Union(typesToDelete).Distinct().ToList();

            if (types.Any(t => !DataStores.ContainsKey(t)))
            {
                throw new NotSupportedException("Type not registered");
            }


            // do not work too hard if it's single stage
            if (transactionRequest.IsSingleStage)
            {
                ProcessSingleStageTransactionRequest(transactionRequest, client);
                return;
            }


            if (!AcquireWriteLock(client, types, transactionRequest.TransactionId))
            {
                return;
            }

            Dbg.Trace($"S: lock acquired by all clients for transaction {transactionRequest.TransactionId}");


            // Second register a durable delayed transaction. It can be cancelled later

            try
            {
                // check the conditions (in case of conditional update)
                int index = 0;
                foreach (var condition in transactionRequest.Conditions)
                {
                    if (!condition.IsEmpty())
                    {
                        var ds = DataStores[condition.TypeName];

                        ds.CheckCondition(transactionRequest.ItemsToPut[index].PrimaryKey, condition);
                    }

                    index++;
                }

                Dbg.Trace($"S: begin writing delayed transaction {transactionRequest.TransactionId}");
                PersistenceEngine?.NewTransaction(new MixedTransaction
                {
                    ItemsToDelete = transactionRequest.ItemsToDelete,
                    ItemsToPut    = transactionRequest.ItemsToPut
                },
                                                  true
                                                  );

                client.SendResponse(new ReadyResponse());


                Dbg.Trace($"S: end writing delayed transaction {transactionRequest.TransactionId}");
            }
            catch (CacheException e)
            {
                Dbg.Trace($"error in first stage:{e.Message} server {ShardIndex}");
                client.SendResponse(new ExceptionResponse(e, e.ExceptionType));
                // failed to write a durable transaction so stop here

                // unlock
                foreach (var type in types)
                {
                    if (DataStores[type].Lock.IsWriteLockHeld)
                    {
                        DataStores[type].Lock.ExitWriteLock();
                    }
                }
                return;
            }
            catch (Exception e)
            {
                Dbg.Trace($"error in first stage:{e.Message} server {ShardIndex}");
                client.SendResponse(new ExceptionResponse(e));
                // failed to write a durable transaction so stop here

                // unlock
                foreach (var type in types)
                {
                    if (DataStores[type].Lock.IsWriteLockHeld)
                    {
                        DataStores[type].Lock.ExitWriteLock();
                    }
                }
                return;
            }


            try
            {
                Dbg.Trace($"S: begin waiting for client go {transactionRequest.TransactionId}");
                var answer = client.ShouldContinue();
                Dbg.Trace($"S: end waiting for client go answer = {answer}");

                if (answer.HasValue) // the client has answered
                {
                    if (answer.Value)
                    {
                        // update the data in memory
                        var dataRequests = transactionRequest.SplitByType();

                        foreach (var dataRequest in dataRequests)
                        {
                            if (!DataStores.ContainsKey(dataRequest.FullTypeName))
                            {
                                throw new NotSupportedException(
                                          $"The type {dataRequest.FullTypeName} is not registered");
                            }
                            DataStores[dataRequest.FullTypeName].ProcessRequest(dataRequest, client, null);
                        }

                        ServerLog.LogInfo(
                            $"S: two stage transaction committed successfully on server {ShardIndex} {transactionRequest.TransactionId}");
                    }
                    else
                    {
                        ServerLog.LogWarning(
                            $"S: two stage transaction cancelled by client on server {ShardIndex} {transactionRequest.TransactionId}");

                        // cancel the delayed transaction
                        PersistenceEngine?.CancelDelayedTransaction();
                    }
                }
                else // the client failed to answer in a reasonable delay (which is less than the delay to commit a delayed transaction )
                {
                    PersistenceEngine?.CancelDelayedTransaction();
                }
            }
            catch (Exception e)
            {
                ServerLog.LogInfo($"error in the second stage of a transaction:{e.Message}");
            }


            // unlock
            foreach (var type in types)
            {
                if (DataStores[type].Lock.IsWriteLockHeld)
                {
                    DataStores[type].Lock.ExitWriteLock();
                }
            }
        }
示例#10
0
        public void UpdateServerLog(string message, Color sendercolor)
        {
            try
            {
                if (ServerLog.InvokeRequired)
                {
                    Invoke(updateServerLogDelegate, message, sendercolor);
                }
                else
                {
                    ServerLog.SelectionStart  = ServerLog.TextLength;
                    ServerLog.SelectionLength = 0;
                    ServerLog.SelectionColor  = sendercolor;
                    List <string> messageComponents = new List <string>();
                    if (message.Contains(':'))
                    {
                        messageComponents.Add(message.Substring(0, message.IndexOf(':') + 1));
                        messageComponents.Add(message.Substring(message.IndexOf(':') + 1) + "\n");
                    }
                    else
                    {
                        messageComponents.Add(message + "\n");
                    }
                    for (int i = 0; i < messageComponents.Count; ++i)
                    {
                        while (messageComponents[i].Contains("<color"))
                        {
                            int      startOfTag  = messageComponents[i].IndexOf("<color (");
                            int      endOfTag    = messageComponents[i].IndexOf(")>");
                            string   colorString = messageComponents[i].Substring(startOfTag + 8, endOfTag - startOfTag - 8);
                            string[] colors      = colorString.Split(',');
                            ServerLog.AppendText(messageComponents[i].Substring(0, startOfTag));
                            if (colors.Length == 3)
                            {
                                int r = 0, g = 0, b = 0;
                                if (Int32.TryParse(colors[0], out r) && Int32.TryParse(colors[1], out g) && Int32.TryParse(colors[2], out b))
                                {
                                    ServerLog.SelectionColor = Color.FromArgb(r, g, b);
                                }
                            }
                            ServerLog.AppendText(messageComponents[i].Substring(endOfTag + 2, messageComponents[i].IndexOf("</color>") - endOfTag - 2));
                            messageComponents[i]     = messageComponents[i].Substring(messageComponents[i].IndexOf("</color>") + 8);
                            ServerLog.SelectionColor = ServerLog.ForeColor;
                        }
                        ServerLog.AppendText(messageComponents[i]);
                        ServerLog.SelectionColor = ServerLog.ForeColor;
                    }

                    ServerLog.SelectionStart = ServerLog.Text.Length;
                    ServerLog.ScrollToCaret();
                }
            }
            catch (System.InvalidOperationException e)
            {
                Console.WriteLine(e.Message);
            }
            catch (InvalidAsynchronousStateException e)
            {
                Console.WriteLine(e.Message);
            }
        }
示例#11
0
        public async Task Load(string path)
        {
            await Task.Factory.StartNew(() => { LoadImpl(path); });

            ServerLog.Debug("DBCStore", "Loaded {0} entries from {1}", NumRecords, path);
        }
示例#12
0
        public async Task Load(string constring)
        {
            await LoadImpl(await CreateConnection(constring));

            ServerLog.Debug("DataStore", "Loaded {0} entries from {1}", NumRecords, TableName);
        }