Пример #1
0
 private void ReceiveCallback(IAsyncResult ar)
 {
     try
     {
         RecvLength = Socket.EndReceive(ar);
         if (RecvLength == 0)
         {
             ///发送端关闭
             Console.WriteLine("{0} 发送端{1}连接关闭", TmTimerTool.CurrentTime(), Socket.RemoteEndPoint);
             IsRunning = false;
             Dispose();
             return;
         }
         else
         {
             AddRange(RecvBuffList, Buffer, RecvLength);
         }
         ///触发事件 解析缓存池RecvBuffList<byte> 读取数据字节
         ParsingBytes();
         ///继续接收来自来客户端的数据
         Socket.BeginReceive(Buffer, 0, BufferSize, SocketFlags.None, new AsyncCallback(this.ReceiveCallback), this);
     }
     catch (Exception ex)
     {
         Console.WriteLine(TmTimerTool.CurrentTime() + " " + ex.ToString());
         IsRunning = false;
         Dispose();
     }
 }
Пример #2
0
 public override void OnSendMvcParameters()
 {
     try
     {
         while (SendParameters.Count > 0)
         {
             TmParameter mvc = SendParameters.Dequeue();
             while (mvc.Keys.Count > 0)
             {
                 TmTcpSession tpeer;
                 TPeers.TryGetValue(mvc.Keys[0], out tpeer);
                 ///用Json将参数(MvcParameter),序列化转换成字符串(string)
                 string mvcJsons = TmJson.ToString <TmParameter>(mvc);
                 if (tpeer != null)
                 {
                     tpeer.SendString(mvcJsons);
                 }
                 else
                 {
                     Console.WriteLine(TmTimerTool.CurrentTime() + " 没找TPeer,用Key: " + mvc.Keys[0]);
                     break;
                 }
                 mvc.Keys.Remove(mvc.Keys[0]);
             }
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(TmTimerTool.CurrentTime() + " OnSendMvcParameters: " + ex.Message);
     }
 }
Пример #3
0
        //private static string logpath = AppDomain.CurrentDomain.BaseDirectory + "TumoLog/log.txt";
        /// <summary>
        /// 用于控制台
        /// </summary>
        /// <param name="message"></param>
        public static void WriteLine(string message)
        {
            //打开文件,如果文件不存在,则创建一个文件
            string path = consolePath;

            if (!File.Exists(path))
            {
                using (File.Create(path)) { }
            }
            //打开文件,如果文件大于2M,则修改文件名保存备份
            FileInfo fileinfo = new FileInfo(path);

            if (fileinfo.Length > 1024 * 1024 * 2)
            {
                File.Move(path, AppDomain.CurrentDomain.BaseDirectory + TmTimerTool.CurrentTime() + "log.txt");
                if (!File.Exists(path))
                {
                    using (File.Create(path)) { }
                }
            }
            //在文件上写入文本文字
            StreamWriter sw2 = File.AppendText(path);

            sw2.WriteLine(TmTimerTool.CurrentTime() + " " + message);
            sw2.Close();
        }
Пример #4
0
        public override void TmDispose()
        {
            base.TmDispose();
            ///从peers字典中删除
            TmTcpSession tpeer;

            TmTcpSocket.Instance.TPeers.TryGetValue(EcsId, out tpeer);
            if (tpeer != null)
            {
                //删除掉心跳包群中对应的peer
                TmTcpSocket.Instance.TPeers.Remove(EcsId);
            }            ///显示客户端群中的客户端数量
            if (this.GetComponent <TmSession>().Engineer != null)
            {
                TmSoulerDB soulerDB;
                TmObjects.Engineers.TryGetValue(this.GetComponent <TmSession>().Engineer.Id, out soulerDB);
                if (soulerDB != null)
                {
                    TmObjects.Engineers.Remove(this.GetComponent <TmSession>().Engineer.Id);
                }
            }
            Console.WriteLine(TmTimerTool.CurrentTime() + "{0} 服务端{1}断开连接", TmTimerTool.CurrentTime(), EcsId);
            Console.WriteLine(TmTimerTool.CurrentTime() + " 一个客户端:已经中断连接" + " TPeers: " + TmTcpServer.Instance.TPeers.Count);
            Console.WriteLine(TmTimerTool.CurrentTime() + " 一个角色:已经离线" + " Engineers: " + TmObjects.Engineers.Count);
        }
Пример #5
0
        private void ParsingBytes()
        {
            ///将本次要接收的消息头字节数置0
            int iBytesHead = 0;
            ///将本次要剪切的字节数置0
            int iBytesBody = 0;

            try
            {
                if (isHead)
                {
                    ///如果当前需要接收的字节数小于缓存池RecvBuffList,进行下一步操作
                    if (surHL <= RecvBuffList.Count)
                    {
                        iBytesHead = surHL;
                        surHL      = 0;
                    }
                    if (surHL == 0)
                    {
                        isHead = false;
                        isBody = true;
                        ///接收消息体(消息体的长度存储在消息头的0至4索引位置的字节里)
                        byte[] HeadBytes = new byte[iBytesHead];
                        ///将接收到的字节数的消息头保存到HeadBytes,//减去已经接收到的字节数
                        CutTo(RecvBuffList, HeadBytes, 0, iBytesHead);
                        int msgLength = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(HeadBytes, 0));
                        surBL = msgLength;
                    }
                }
                if (isBody)
                {
                    ///如果当前需要接收的字节数大于0,则循环接收
                    if (surBL <= RecvBuffList.Count)
                    {
                        iBytesBody = surBL;
                        surBL      = 0;               ///归零进入下一步操作
                    }
                    if (surBL == 0)
                    {
                        isBody = false;
                        isHead = true;
                        surHL  = 4;
                        ///一个消息包接收完毕,解析消息包
                        byte[] BodyBytes = new byte[iBytesBody];
                        CutTo(RecvBuffList, BodyBytes, 0, iBytesBody);
                        ///一个消息包接收完毕,解析消息包
                        string mvcString = Encoding.UTF8.GetString(BodyBytes, 0, BodyBytes.Length);
                        Console.WriteLine(TmTimerTool.CurrentTime() + " Recv {0} Bytes. ThreadId:{1}", BodyBytes.Length, Thread.CurrentThread.ManagedThreadId);
                        TmParameter parameter = TmJson.ToObject <TmParameter>(mvcString);
                        ///这个方法用来处理参数Mvc,并让结果给客户端响应(当客户端发起请求时调用)
                        OnTransferParameter(this, parameter);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(TmTimerTool.CurrentTime() + ex.ToString());
                Dispose();
            }
        }
Пример #6
0
        ///供程序员显式调用的Dispose方法
        public virtual void Dispose()
        {
            if (!isDisposed)
            {
                TmObjects.Components.Remove(EcsId);
                TmDispose();               /// 为继承类释放时使用,用抽象方法
                GC.SuppressFinalize(this); ///GC不用二次释放this资源
                isDisposed = true;

                try
                {
                    if (Parent != null)
                    {
                        TmComponent tm;
                        Parent.Components.TryGetValue(this.GetType().Name, out tm);
                        if (tm != null)
                        {
                            Parent.Components.Remove(this.GetType().Name);
                        }
                        Parent = null;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(TmTimerTool.CurrentTime() + " ex:" + ex.Message + " TmComponent释放资源异常...");
                }
            }
        }
Пример #7
0
 public override void OnSendMvcParameters()
 {
     try
     {
         while (SendParameters.Count > 0)
         {
             TmParameter mvc = SendParameters.Dequeue();
             ///用Json将参数(MvcParameter),序列化转换成字符串(string)
             string mvcJsons = TmJson.ToString <TmParameter>(mvc);
             if (TClient != null)
             {
                 TClient.SendString(mvcJsons);
             }
             //else
             //{
             //    if (IsRunning)
             //    {
             //        IsRunning = false;
             //        StartConnect();
             //        Console.WriteLine(TmTimerTool.CurrentTime() + " TClient is Null. new TClient() 重新连接。");
             //    }
             //}
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(TmTimerTool.CurrentTime() + " SendMvcParameters: " + ex.Message);
     }
 }
Пример #8
0
        }///与服务器连接时调用

        public override void TmDispose()
        {
            base.TmDispose();
            if (TmTcpSocket.Instance.TClient != null && TmTcpSocket.Instance.TClient.EcsId == this.EcsId)
            {
                TmTcpSocket.Instance.TClient = null;
            }
            Console.WriteLine("{0} 服务端{1}断开连接", TmTimerTool.CurrentTime(), EcsId);
        }///与服务器断开时调用
Пример #9
0
 public override void StartListen()
 {
     if (!IsRunning)
     {
         netSocket.Bind(new IPEndPoint(this.address, this.Port));
         netSocket.Listen(MaxListenCount);
         netSocket.BeginAccept(new AsyncCallback(this.AcceptCallback), netSocket);
         Console.WriteLine("{0} 服务启动,监听{1}成功", TmTimerTool.CurrentTime(), netSocket.LocalEndPoint);
     }
 }
Пример #10
0
        public static string GetId()
        {
            string tmId = "";

            idCount += 1;
            if (idCount > 4000)
            {
                idCount = 1400;
            }
            tmId = TmTimerTool.IdCurrentTime() + idCount.ToString();
            return(tmId);
        }
Пример #11
0
        } ///发送信息给客户端

        private void SendCallback(IAsyncResult ar)
        {
            try
            {
                Socket client    = (Socket)ar.AsyncState;
                int    bytesSent = client.EndSend(ar);
                Console.WriteLine(TmTimerTool.CurrentTime() + " Sent {0} Bytes. ThreadId:{1}", bytesSent, Thread.CurrentThread.ManagedThreadId);
            }
            catch (Exception ex)
            {
                Console.WriteLine(TmTimerTool.CurrentTime() + ex.ToString());
            }
        }
Пример #12
0
        public void AddComponent <T>(T tm) where T : TmComponent
        {
            TmComponent com;
            bool        have = Comopnents.TryGetValue(typeof(T).Name, out com);

            if (have)
            {
                Console.WriteLine(TmTimerTool.CurrentTime() + typeof(T).Name + "此类组件已添加");
            }
            else
            {
                Comopnents.Add(typeof(T).Name, tm);
            }
        }
Пример #13
0
 public override void TmDispose()
 {
     base.TmDispose();
     try
     {
         Socket.Shutdown(SocketShutdown.Both);
         IsRunning = false;
         Socket.Close();
         Socket = null;
         Console.WriteLine(TmTimerTool.CurrentTime() + " EcsId:" + EcsId + " TmTcpSession释放资源");
     }
     catch (Exception ex)
     {
         Console.WriteLine(TmTimerTool.CurrentTime() + " " + ex.Message);
     }
 }
Пример #14
0
        public override void OnConnect()
        {
            ///显示与客户端连接
            Console.WriteLine("{0} 客户端{1}连接成功", TmTimerTool.CurrentTime(), Socket.RemoteEndPoint);
            TmTcpSession tpeer = null;
            bool         yes1  = TmTcpSocket.Instance.TPeers.TryGetValue(this.EcsId, out tpeer);

            if (yes1 != true)
            {
                ///tpeers已经加入字典
                TmTcpSocket.Instance.TPeers.Add(this.EcsId, this);
                Console.WriteLine(TmTimerTool.CurrentTime() + " ComponentId: " + this.EcsId + " 已经加入字典");
            }
            ///显示客户端群中的客户端数量
            Console.WriteLine(TmTimerTool.CurrentTime() + " TPeers Count: " + TmTcpServer.Instance.TPeers.Count);
        }
Пример #15
0
        public void AddComponent <T>(T tm) where T : TmComponent
        {
            TmComponent tem;

            Components.TryGetValue(typeof(T).Name, out tem);
            if (tem == null)
            {
                tm.Parent = this;
                Components.Add(typeof(T).Name, tm);
                Console.WriteLine(TmTimerTool.CurrentTime() + " 实例{0},成功添加组件{1}.", this.GetType().Name, typeof(T).Name);
            }
            else
            {
                Console.WriteLine(TmTimerTool.CurrentTime() + " 此类型组件 {} 已存在!", typeof(T).Name);
            }
        }
Пример #16
0
        public T GetComponent <T>() where T : class
        {
            string      name = typeof(T).Name;
            TmComponent tem;

            Components.TryGetValue(name, out tem);
            if (tem != null)
            {
                return(tem as T);
            }
            else
            {
                Console.WriteLine(TmTimerTool.CurrentTime() + tem.GetType().Name + "此类型组件不存在!");
                return(null);
            }
        }
Пример #17
0
        }/// 队列数据

        #endregion
        #region SendString
        public void SendString(string mvcString)
        {
            if (null == Socket.Handle || !Socket.Connected)
            {
                Console.WriteLine(TmTimerTool.CurrentTime() + " 连接已中断!!!");
                IsRunning = false;
                return;
            }
            ///将字符串(string)转换成字节(byte)
            byte[] jsonsByte = Encoding.UTF8.GetBytes(mvcString);
            ///消息包长度
            int sendLength = 4 + jsonsByte.Length;

            ///定义数据包(消息长度4字节 + 消息体长度)
            byte[] MsgsByte = new byte[sendLength];
            ///先存入消息长度数值4个字节
            BitConverter.GetBytes(IPAddress.HostToNetworkOrder(jsonsByte.Length)).CopyTo(MsgsByte, 0);
            ///然后存入信息体字节
            jsonsByte.CopyTo(MsgsByte, 4);
            AddRange(SendBuffList, MsgsByte, MsgsByte.Length);
            while (sendLength > 0)
            {
                try
                {
                    if (sendLength <= BufferSize)
                    {
                        byte[] temBytes = new byte[sendLength];
                        CutTo(SendBuffList, temBytes, 0, sendLength);
                        Socket.BeginSend(temBytes, 0, temBytes.Length, 0, new AsyncCallback(this.SendCallback), Socket);
                        sendLength = 0;
                    }
                    else
                    {
                        byte[] temBytes = new byte[BufferSize];
                        CutTo(SendBuffList, temBytes, 0, BufferSize);
                        sendLength -= BufferSize;
                        Socket.BeginSend(temBytes, 0, temBytes.Length, 0, new AsyncCallback(this.SendCallback), Socket);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(TmTimerTool.CurrentTime() + ex.ToString());
                    Dispose();
                }
            }
        } ///发送信息给客户端
Пример #18
0
        private void ConnectCallback(IAsyncResult ar)
        {
            //创建一个Socket接收传递过来的TmSocket
            Socket tcpSocket = (Socket)ar.AsyncState;

            try
            {
                //得到成功的连接
                tcpSocket.EndConnect(ar);
                ///触发事件///创建一个方法接收peerSocket (在方法里创建一个peer来处理读取数据//开始接受来自该客户端的数据)
                TmReceiveSocket(tcpSocket);
                Console.WriteLine("{0} 连接服务器成功 {1}", TmTimerTool.CurrentTime(), tcpSocket.RemoteEndPoint.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Пример #19
0
        public void RemoveComponent <T>()
        {
            string      name = typeof(T).Name;
            TmComponent tem;

            Components.TryGetValue(name, out tem);
            if (tem != null)
            {
                Components.Remove(name);
                tem.Parent = null;
                Console.WriteLine(TmTimerTool.CurrentTime() + " 实例 {0} 删除组件 {1}", this.GetType().Name, typeof(T).Name);
                tem.Dispose();
            }
            else
            {
                Console.WriteLine(TmTimerTool.CurrentTime() + name + "此类型组件不存在!");
            }
        }
Пример #20
0
        void CheckSession(TmEntity entity)
        {
            TmCoolDown cd = entity.GetComponent <TmCoolDown>();

            if (!cd.Counting)
            {
                entity.Dispose();
                //TmTcpSocket.Instance.StartConnect();
            }
            else
            {
                //发送心跳检测(并等待签到,签到入口在TmTcpSession里,双向发向即:客户端向服务端发送,服务端向客户端发送)
                TmParameter mvc = TmParameterTool.ToParameter(TenCode.EessionCD, ElevenCode.Login);
                mvc.Keys.Add(entity.EcsId);
                TmTcpSocket.Instance.Send(mvc);
            }
            Console.WriteLine(TmTimerTool.CurrentTime() + " CdCount:{0}-{1} ", cd.CdCount, cd.MaxCdCount);
            //Debug.Log(TmTimerTool.CurrentTime() + " CdCount:" + cd.CdCount + "-" + cd.MaxCdCount);
        }
Пример #21
0
 public override void Dispose()
 {
     base.Dispose();
     TmObjects.Entities.Remove(this);
     try
     {
         if (Components.Count > 0)
         {
             foreach (var tem in Components.Values)
             {
                 tem.Dispose();
             }
             Console.WriteLine(TmTimerTool.CurrentTime() + " EcsId:" + EcsId + " TmEntity释放资源");
         }
         Components.Clear();
     }
     catch (Exception ex)
     {
         Console.WriteLine(TmTimerTool.CurrentTime() + " ex: " + ex.Message + " TmEntity释放资源异常...");
     }
 }
Пример #22
0
 public override void OnConnect()
 {
     ///显示与客户端连接
     Console.WriteLine("{0} 服务端{1}连接成功", TmTimerTool.CurrentTime(), EcsId);
 }///与服务器连接时调用
Пример #23
0
 public override void Dispose()
 {
     base.Dispose();
     Close();       ///关闭Timer时钟
     Console.WriteLine(TmTimerTool.CurrentTime() + " EcsId:" + EcsId + " TmSystem释放资源");
 }