Exemple #1
0
        /*初始化服务器*/
        private void StartListening()
        {
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, portNum);


            // 创建TCP/IP socket
            listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //绑定Socket到本地端口和监听输入连接
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(100);
                LoggerHelper.Debug("Waiting for a connection...");
                while (m_isRunning)
                {
                    allDone.Reset();
                    //结束回调,只能连接一台客户端
                    listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
                    //手动阻塞
                    allDone.WaitOne();
                }
            }
            catch (Exception e)
            {
                LoggerHelper.Except(e);
            }
        }
Exemple #2
0
 public void StartMatch(ClientListener client, Pluto pluto)
 {
     LoggerHelper.Debug("StartMatch");
     foreach (var item in m_roomsData.Values)
     {
         if (!item.IsBusy)
         {
             var canStart = item.AddClient(client);
             var ecap     = new EntityCellAttachedPluto();
             var res      = ecap.ServerEncode(GetCellData(client));
             client.Send(res);
             AOINew(client);
             AOIEntityies(client);
             if (canStart)
             {
                 StartBattle(client, pluto);
             }
             LoggerHelper.Debug("StartMatch " + canStart);
             return;
         }
     }
     CreatRoom(client, (int)pluto.Arguments[0], (int)pluto.Arguments[1]);
     if ((int)pluto.Arguments[0] == 1)//单人模式
     {
         StartBattle(client, pluto);
     }
 }
Exemple #3
0
 /**进行发包
  * 发包组成:包头+序号+包体
  * 1、包头内容由:‘序号长度+包头长度+包体长度’组成
  * **/
 private void sendData(byte[] data)
 {
     //int seriNum = -1;                                                                                          //序号
     byte[] headBytes = BitConverter.GetBytes(m_headLengthConverter.VTypeLength + RESERVE_SIZE + data.Length); //包头
     byte[] sendBytes = new byte[headBytes.Length + RESERVE_SIZE + data.Length];                               //发送包
     //if (CompareMsgHead(m_baseRpcCallHead, data) || CompareMsgHead(m_cellRpcCallHead, data))
     //{//加序号,防重发
     //    seriNum = getSerialNumber();
     //}
     headBytes.CopyTo(sendBytes, 0);
     //if (seriNum >= 0) VUInt16.Instance.Encode(seriNum).CopyTo(sendBytes, headBytes.Length);                    //需发送序号
     data.CopyTo(sendBytes, headBytes.Length + RESERVE_SIZE);
     if (Connected())
     {
         //client.Send(sendBytes, 0, sendBytes.Length, SocketFlags.None);
         client.BeginSend(sendBytes, 0, sendBytes.Length, SocketFlags.None, null, null);  //new AsyncCallback(onSend), seriNum
         //LoggerHelper.Info("send: " + data.PackArray());
         //LoggerHelper.Info("发送包Len:" + sendBytes.Length + ",bodyLen:" + data.Length + ",thread:" + (thread != null ? thread.IsAlive : false) + ",timeId:" + timeId);
     }
     else
     {
         if (!isPrintClose)
         {
             isPrintClose = true; LoggerHelper.Debug("-sendData() 服务器[" + ip + ":" + port + "] 已关闭!");
         }
     }
 }
Exemple #4
0
        /**重试连接**/
        private void tryConnect()
        {
            if (Connected())
            {
                return;
            }
            isReceiving = false;
            if (!isOpenTryLink)
            {
                closeCallback();
                return;
            }

            if (tryNum++ < maxTryNum)
            {//重连
                LoggerHelper.Debug("-connect() [" + ip + ":" + port + "] 第" + tryNum + "次重连接");
                Connect(ip, port);
            }
            else
            {//连接失败
                LoggerHelper.Error("-tryConnect() [" + ip + ":" + port + "][Fail] 已超过最大重连次数maxTryNum:" + maxTryNum + ",tryNum:" + tryNum);
                if (netStatusListener != null)
                {
                    netStatusListener(LINK_FAIL);
                }
            }
        }
Exemple #5
0
        public static Dictionary <string, string> GetResourcePathMap()
        {
            var sw = new System.Diagnostics.Stopwatch();

            sw.Start();
            var result = new Dictionary <string, string>();

            foreach (var item in metaOfResource)
            {
                var name = Utils.GetFileName(item.Key);
                if (result.ContainsKey(name))
                {
                    LoggerHelper.Warning("Same resource name; " + name);
                }
                else
                {
                    result.Add(name, item.Key);
                }
            }
            sw.Stop();
            LoggerHelper.Debug("metaOfResource: " + metaOfResource.Count);
            LoggerHelper.Debug("time: " + sw.ElapsedMilliseconds);
            //Mogo.Util.LoggerHelper.Debug(result.PackMap(mapSpriter: '\n'));
            return(result);
        }
Exemple #6
0
 public void Connect(string IP, int Port)
 {
     lock (this.m_tcpClientLocker)
     {
         if ((this.m_socket != null) && this.m_socket.Connected)
         {
             throw new Exception("Exception. the tcpClient has Connectted.");
         }
         try
         {
             LoggerHelper.Debug("Connect.m_ConnectChecker: " + this.m_ConnectChecker, true, 0);
             this.m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             this.m_socket.ReceiveBufferSize = 0xffff;
             this.m_socket.NoDelay           = true;
             this.m_socket.Connect(IP, Port);
             if (this.m_socket != null)
             {
                 if (this.m_receiveThread == null)
                 {
                     this.m_receiveThread = new Thread(new ThreadStart(this.DoReceive));
                     this.m_receiveThread.IsBackground = true;
                 }
                 if (!this.m_receiveThread.IsAlive)
                 {
                     this.m_receiveThread.Start();
                 }
             }
         }
         catch (Exception exception)
         {
             throw new Exception("Exception. the tcpClient do connecting error." + exception);
         }
     }
 }
Exemple #7
0
        private void DoReceive()
        {
            //读取流
            do
            {
                bytesRead = 0;
                try
                {
                    int size = MAX_BUFFER_SIZE - m_nRecvBufferSize;
                    if (size > 0)
                    {
                        bytesRead          = m_socket.Receive(m_recvBuffer, m_nRecvBufferSize, size, SocketFlags.None);
                        m_nRecvBufferSize += bytesRead;
                        if (bytesRead == 0)
                        {//读的长度为0
                            bytesRead = 1;
                        }
                    }
                    else
                    {
                        bytesRead = 1;//缓存不够时继续循环,后面会对缓存数据进行处理
                        LoggerHelper.Warning("buffer not enough");
                    }
                }
                catch (ObjectDisposedException)
                {
                    // 网络流已被关闭,结束接收数据
                    LoggerHelper.Error("tcp close");
                }
                catch (IOException ioex)
                {
                    //捕获WSACancelBlockingCall()导致的异常。
                    //原因:强迫终止一个在进行的阻塞调用。
                    //可直接捕获忽略,应该不会有不良影响。
                    //LoggerHelper.Error("WSACancelBlockCall");
                    LoggerHelper.Except(ioex);
                }
                catch (Exception ex)
                {
                    LoggerHelper.Except(ex);
                }
                //LoggerHelper.Debug("DataReceive: " + bytesRead);
                SplitPackets();
            } while (bytesRead > 0);

            lock (m_connectCheckerLocker)
                if (m_ConnectChecker > 0)
                {
                    m_ConnectChecker--;
                    LoggerHelper.Debug("Disconnected.m_ConnectChecker: " + m_ConnectChecker);
                }
                else
                {
                    LoggerHelper.Error("receive bytes " + bytesRead);
                    TimerHeap.AddTimer(1000, 0, OnNetworkDisconnected);
                }

            LoggerHelper.Debug("DataReceiveComplete");
        }
Exemple #8
0
        private void onSend(IAsyncResult result)
        {
            int seriNum = (int)result.AsyncState;

            if (seriNum > 0)
            {
                LoggerHelper.Debug("seriNum:" + seriNum + " 包已发送,connected:" + Connected());
            }
        }
Exemple #9
0
        /*连接回调*/
        private void AcceptCallback(IAsyncResult ar)
        {
            // 主线程继续
            allDone.Set();

            // 得到客户端Socket请求
            Socket listener = (Socket)ar.AsyncState;
            Socket handler  = listener.EndAccept(ar);

            AddClient(handler);
            LoggerHelper.Debug("Client linked: " + handler.RemoteEndPoint.ToString());
        }
Exemple #10
0
 private void DoReceive()
 {
     do
     {
         this.bytesRead = 0;
         try
         {
             int size = 0xffff - this.m_nRecvBufferSize;
             if (size > 0)
             {
                 this.bytesRead          = this.m_socket.Receive(this.m_recvBuffer, this.m_nRecvBufferSize, size, SocketFlags.None);
                 this.m_nRecvBufferSize += this.bytesRead;
                 if (this.bytesRead == 0)
                 {
                     this.bytesRead = 1;
                 }
             }
             else
             {
                 this.bytesRead = 1;
                 LoggerHelper.Warning("buffer not enough", true);
             }
         }
         catch (ObjectDisposedException)
         {
             LoggerHelper.Error("tcp close", true);
         }
         catch (IOException exception)
         {
             LoggerHelper.Except(exception, null);
         }
         catch (Exception exception2)
         {
             LoggerHelper.Except(exception2, null);
         }
         this.SplitPackets();
     }while (this.bytesRead > 0);
     lock (this.m_connectCheckerLocker)
     {
         if (this.m_ConnectChecker > 0)
         {
             this.m_ConnectChecker--;
             LoggerHelper.Debug("Disconnected.m_ConnectChecker: " + this.m_ConnectChecker, true, 0);
         }
         else
         {
             LoggerHelper.Error("receive bytes " + this.bytesRead, true);
             TimerHeap.AddTimer(0x3e8, 0, this.OnNetworkDisconnected);
         }
     }
     LoggerHelper.Debug("DataReceiveComplete", true, 0);
 }
Exemple #11
0
        private static List <T> LoadXMLText <T>(string text)
        {
            Exception exception;
            List <T>  list = new List <T>();

            try
            {
                if (string.IsNullOrEmpty(text))
                {
                    return(list);
                }
                Type type = typeof(T);
                Dictionary <int, Dictionary <string, string> > dictionary = XMLParser.LoadIntMap(XMLParser.LoadXML(text), text);
                PropertyInfo[] properties = type.GetProperties(~BindingFlags.Static);
                foreach (KeyValuePair <int, Dictionary <string, string> > pair in dictionary)
                {
                    object obj2 = type.GetConstructor(Type.EmptyTypes).Invoke(null);
                    foreach (PropertyInfo info in properties)
                    {
                        if (info.Name == "id")
                        {
                            info.SetValue(obj2, pair.Key, null);
                        }
                        else
                        {
                            try
                            {
                                if (pair.Value.ContainsKey(info.Name))
                                {
                                    object obj3 = Utils.GetValue(pair.Value[info.Name], info.PropertyType);
                                    info.SetValue(obj2, obj3, null);
                                }
                            }
                            catch (Exception exception1)
                            {
                                exception = exception1;
                                LoggerHelper.Debug(string.Concat(new object[] { "LoadXML error: ", pair.Value[info.Name], " ", info.PropertyType }), true, 0);
                                LoggerHelper.Except(exception, null);
                            }
                        }
                    }
                    list.Add((T)obj2);
                }
            }
            catch (Exception exception2)
            {
                exception = exception2;
                LoggerHelper.Except(exception, null);
                LoggerHelper.Error("error text: \n" + text, true);
            }
            return(list);
        }
Exemple #12
0
        /// <summary>
        /// 得到所有孩子,无层次限制
        /// </summary>
        static public List <Transform> GetAllChild(Transform transform)
        {
            LoggerHelper.Debug(transform.name);
            List <Transform> children = new List <Transform>();

            children.AddRange(transform.GetComponentsInChildren <Transform>());
            foreach (Transform child in children)
            {
                children.AddRange(GetAllChild(child));
            }

            return(children);
        }
Exemple #13
0
 public TCPClientWorker()
 {
     if (this.m_sendThread == null)
     {
         LoggerHelper.Debug("init AsynSend", true, 0);
         this.m_sendThread = new Thread(new ThreadStart(this.AsynSend));
         this.m_sendThread.IsBackground = true;
     }
     if (!this.m_sendThread.IsAlive)
     {
         LoggerHelper.Debug("Start AsynSend: " + this.m_asynSendSwitch, true, 0);
         this.m_sendThread.Start();
     }
 }
Exemple #14
0
        private static List <T> LoadXMLText <T>(string text)
        {
            List <T> list = new List <T>();

            try
            {
                if (String.IsNullOrEmpty(text))
                {
                    return(list);
                }
                Type type = typeof(T);
                var  xml  = XMLParser.LoadXML(text);
                Dictionary <Int32, Dictionary <String, String> > map = XMLParser.LoadIntMap(xml, text);
                var props = type.GetProperties(~System.Reflection.BindingFlags.Static);
                foreach (var item in map)
                {
                    var obj = type.GetConstructor(Type.EmptyTypes).Invoke(null);
                    foreach (var prop in props)
                    {
                        if (prop.Name == "id")
                        {
                            prop.SetValue(obj, item.Key, null);
                        }
                        else
                        {
                            try
                            {
                                if (item.Value.ContainsKey(prop.Name))
                                {
                                    var value = Utils.GetValue(item.Value[prop.Name], prop.PropertyType);
                                    prop.SetValue(obj, value, null);
                                }
                            }
                            catch (Exception ex)
                            {
                                LoggerHelper.Debug("LoadXML error: " + item.Value[prop.Name] + " " + prop.PropertyType);
                                LoggerHelper.Except(ex);
                            }
                        }
                    }
                    list.Add((T)obj);
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.Except(ex);
                LoggerHelper.Error("error text: \n" + text);
            }
            return(list);
        }
Exemple #15
0
 /**关闭连接**/
 public void Close()
 {
     stopReceive();
     //OnNetworkDisconnected = null;
     if (client != null)
     {
         client.Close();
     }
     if (timeId > 0)
     {
         TimerHeap.DelTimer(timeId);
     }
     LoggerHelper.Debug("-close() connected:" + Connected() + " 已断开与服务器[" + ip + ":" + port + "]连接!");
 }
Exemple #16
0
        /// <summary>
        /// 每帧调用, 发送数据。
        /// 并包处理
        /// </summary>
        private void DoSend()
        {
            lock (m_tcpClientLocker)
            {
                if ((m_socket == null) || (m_socket.Connected == false))
                {
                    return;
                }
            }
            int nTotalLength = 0;

            // 并包
            lock (m_sendQueueLocker)
            {
                if (m_sendQueue.Count == 0)
                {
                    return;
                }
                while ((nTotalLength < MAX_BUFFER_SIZE) && m_sendQueue.Count > 0)
                {
                    byte[] packet = m_sendQueue.Peek();
                    if (nTotalLength + RESERVE_SIZE + packet.Length < MAX_BUFFER_SIZE)
                    {
                        byte[] length = m_headLengthConverter.Encode((uint)(packet.Length + RESERVE_SIZE + m_headLengthConverter.VTypeLength));
                        length.CopyTo(m_sendBuffer, nTotalLength);
                        nTotalLength += length.Length;
                        nTotalLength += RESERVE_SIZE;
                        packet.CopyTo(m_sendBuffer, nTotalLength);
                        nTotalLength += packet.Length;
                        m_sendQueue.Dequeue();
                    }
                    else
                    {
                        break;
                    }
                }
            }
            // 真正发包到服务器
            try
            {
                m_socket.Send(m_sendBuffer, 0, nTotalLength, SocketFlags.None);
                // 清空发送缓存
                System.Array.Clear(m_sendBuffer, 0, MAX_BUFFER_SIZE);
            }
            catch (Exception e)
            {
                LoggerHelper.Debug("stream write error : " + e.ToString());
            }
        }
Exemple #17
0
        private void DoSend()
        {
            object obj2;

            lock ((obj2 = this.m_tcpClientLocker))
            {
                if (!((this.m_socket != null) && this.m_socket.Connected))
                {
                    return;
                }
            }
            int index = 0;

            lock ((obj2 = this.m_sendQueueLocker))
            {
                if (this.m_sendQueue.Count == 0)
                {
                    return;
                }
                while ((index < 0xffff) && (this.m_sendQueue.Count > 0))
                {
                    byte[] buffer = this.m_sendQueue.Peek();
                    if (((index + 2) + buffer.Length) < 0xffff)
                    {
                        byte[] buffer2 = this.m_headLengthConverter.Encode((uint)((buffer.Length + 2) + this.m_headLengthConverter.VTypeLength));
                        buffer2.CopyTo(this.m_sendBuffer, index);
                        index += buffer2.Length;
                        index += 2;
                        buffer.CopyTo(this.m_sendBuffer, index);
                        index += buffer.Length;
                        this.m_sendQueue.Dequeue();
                    }
                    else
                    {
                        goto Label_012A;
                    }
                }
            }
            Label_012A :;
            try
            {
                this.m_socket.Send(this.m_sendBuffer, 0, index, SocketFlags.None);
                Array.Clear(this.m_sendBuffer, 0, 0xffff);
            }
            catch (Exception exception)
            {
                LoggerHelper.Debug("stream write error : " + exception.ToString(), true, 0);
            }
        }
Exemple #18
0
        public void CreatRoom(ClientListener client, int teamCount, int clientCount)
        {
            LoggerHelper.Debug("CreatRoom " + teamCount + " " + clientCount);
            var room = new RoomData(teamCount, clientCount);

            room.Id    = (uint)Guid.NewGuid().GetHashCode();
            room.MapId = GetRandomMapId();
            room.AddClient(client);
            var ecap = new EntityCellAttachedPluto();
            var res  = ecap.ServerEncode(GetCellData(client));

            client.Send(res);

            m_roomsData.Add(room.Id, room);
        }
 public void Init()
 {
     lock (m_locker)
     {
         if (m_fileFullName == null)
         {
             m_fileFullName = SystemConfig.ResourceFolder + FILE_NAME;
         }
         var sw = new System.Diagnostics.Stopwatch();
         sw.Start();
         Init(m_fileFullName);
         sw.Stop();
         LoggerHelper.Debug("file count: " + m_fileIndexes.Count + " init time: " + sw.ElapsedMilliseconds);
         Close();
     }
 }
 public void Init()
 {
     lock (m_locker)
     {
         if (this.m_fileFullName == null)
         {
             this.m_fileFullName = SystemConfig.ResourceFolder + FILE_NAME;
         }
         Stopwatch stopwatch = new Stopwatch();
         stopwatch.Start();
         this.Init(this.m_fileFullName);
         stopwatch.Stop();
         LoggerHelper.Debug(string.Concat(new object[] { "file count: ", this.m_fileIndexes.Count, " init time: ", stopwatch.ElapsedMilliseconds }), true, 0);
         this.Close();
     }
 }
Exemple #21
0
        public string Start()
        {
            InitData();
            var ip = UtilsEx.GetIP();

            LoggerHelper.Debug(ip);
            ipAddress = ip;
            portNum   = 43998;

            /*创建一个服务器线程并启动*/
            newt = new Thread(new ThreadStart(StartListening));
            newt.IsBackground = true;
            newt.Start();

            return(ip.ToString());
        }
Exemple #22
0
        private void client_Closed(object sender, EventArgs e)
        {
            var c = sender as ClientListener;

            c.ClientData.BelongRoom.RemoveClient(c);
            AOIDelete(c);
            RemoveClient(c);
            //var u = new RpcCallPluto();
            //u.FuncName = "Logout";
            //var result = u.Encode(c.SessionID);
            //lock (m_clientListLocker)
            //    foreach (var item in clientList)
            //    {
            //        item.Send(result);
            //    }
            LoggerHelper.Debug("client_Closed: " + c.ClientData.Id);
        }
Exemple #23
0
        public TCPClientWorker()
        {
            m_sendBuffer          = new byte[MAX_BUFFER_SIZE];
            m_recvBuffer          = new byte[MAX_BUFFER_SIZE];
            m_headLengthConverter = VUInt32.Instance;

            if (m_sendThread == null)
            {
                LoggerHelper.Debug("init AsynSend");
                m_sendThread = new Thread(new ThreadStart(AsynSend));
                m_sendThread.IsBackground = true;
            }

            if (!m_sendThread.IsAlive)
            {
                LoggerHelper.Debug("Start AsynSend: " + m_asynSendSwitch);
                m_sendThread.Start();
            }
        }
Exemple #24
0
        private void OnDataReceive(ClientListener client, Byte[] data)
        {
            var pluto = Pluto.Decode(data);
            var type  = pluto.GetType();

            if (type == typeof(LoginPluto))
            {
                HandleLogin(client, pluto);
            }
            else if (type == typeof(MovePluto))
            {
                HandleMove(client, pluto);
            }
            else if (type == typeof(RpcCallPluto))
            {
                HandleRPCCall(client, pluto);
            }
            else
            {
                LoggerHelper.Debug("Unkown type pluto: " + pluto.GetType().ToString());
            }
        }
Exemple #25
0
        private void HandleLogin(ClientListener client, Pluto pluto)
        {
            client = InitClientData(client, pluto.Arguments[0].ToString());

            var eap = new EntityAttachedPluto();
            var res = eap.ServerEncode(new BaseAttachedInfo()
            {
                typeId = Avatar,
                id     = client.ClientData.Id,
                dbid   = client.ClientData.Dbid,
                props  = new List <EntityPropertyValue>()
                {
                    new EntityPropertyValue(GetEntityDefPropertyByName("Name"), client.ClientData.Name),
                }
            });

            client.Send(res);

            //AOINew(client);
            //AOIEntityies(client);
            LoggerHelper.Debug("Client Login: " + pluto.Arguments[0]);
        }
Exemple #26
0
        public static void ReleaseResource(string relativePath)
        {
            if (String.IsNullOrEmpty(relativePath))
            {
                LoggerHelper.Error("ReleaseResource null path.");
                return;
            }
            var refrence = resources.GetValueOrDefault(relativePath);

            if (refrence != null)
            {
                //if (refrence.referenceCount <= 0)
                //    return;
                //LoggerHelper.Error("Unload true: " + refrence.RelativePath);
                var list = GetResourcesInfo(refrence);
                list.Reverse();
                //Debug.Log(list.PackList('\n'));
                foreach (var item in list)
                {
                    item.referenceCount--;
                    if (item.referenceCount <= 0)
                    {
                        ReleaseResource(item, true);
                    }
                    else
                    {
                        LoggerHelper.Debug("Not 0: " + item.RelativePath);
                    }
                }
                //Debug.Log(list.PackList('\n'));
            }
            else
            {
                //Debug.LogError("Resource to free was not in the Dictionary:" + relativePath);
            }
        }