protected void SendToClient(int clientId, byte[] bytes)
 {
     byte[] length = BitConverter.GetBytes(bytes.Length);
     byte[] send   = new byte[4 + bytes.Length];
     Array.Copy(length, send, 4);
     Array.Copy(bytes, 0, send, 4, bytes.Length);
     ServerLog.LogClient("send:" + send.Length, 2, clientId);
     try
     {
         ClientPool[clientId].socket.BeginSend(send, 0, send.Length, SocketFlags.None, null, null);
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
     }
 }
        public void StartServer()
        {
            _serverListener  = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Listener.NoDelay = true;
            timer            = new Timer(100);
            timer.AutoReset  = true;
            timer.Elapsed   += SendStepAll;
            timer.Enabled    = true;
            Listener.Bind(new IPEndPoint(IPAddress.Parse(this.IP), this.Port));
            Listener.Listen(this._maxConnectNum);
            Listener.BeginAccept(AcceptCallBack, Listener);
            _frameList   = new List <byte[]>();
            _stepMessage = new byte[this._maxConnectNum][];

            ServerLog.LogServer("服务器启动成功", 0);
        }
        protected void ReceiveCallBack(IAsyncResult ar)
        {
            Connection con = (Connection)ar.AsyncState;

            if (!con.ActiveCheck())
            {
                return;
            }

            try
            {
                lock (con)
                {
                    int length = con.socket.EndReceive(ar);
                    ServerLog.LogClient("receive:" + length, 1, con.clientId);
                    if (length <= 0)
                    {
                        ServerLog.LogClient("客户端断开连接:" + ClientPool[con.clientId].socket.LocalEndPoint + "ClientID:" + con.clientId, 0, con.clientId);
                        con.socket.Close();
                        ClientPool.Recover(con.clientId);
                        return;
                    }

                    con.length += length;

                    ProcessData(con);

                    con.socket.BeginReceive(con.readBuff, con.length, con.BuffRemain, SocketFlags.None, ReceiveCallBack, con);
                }
            }
            catch (Exception)
            {
                ServerLog.LogClient("客户端异常终止连接:" + ClientPool[con.clientId].socket.LocalEndPoint + "ClientID:" + con.clientId, 0, con.clientId);

                con.socket.Close();
                ClientPool.Recover(con.clientId);
            }
        }
Exemple #4
0
        public void StartServer(string host, int port, int maxServerCount)
        {
            _serverListener  = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _clientPool      = new IndexObjectPool <Connection>(maxServerCount);
            _frameList       = new List <byte[]>();
            Listener.NoDelay = true;
            timer            = new Timer(100);
            timer.AutoReset  = true;
            timer.Elapsed   += SendStepAll;
            timer.Enabled    = true;
            Listener.Bind(new IPEndPoint(IPAddress.Parse(host), port));
            Listener.Listen(maxServerCount);
            Listener.BeginAccept(AcceptCallBack, Listener);
            _stepMessage = new byte[maxServerCount][];
            framSize     = 0;
            for (int i = 0; i < _stepMessage.Length; i++)
            {
                _stepMessage[i] = new byte[framSize];
            }
            //ClientPool.Clear();

            ServerLog.LogServer("服务器启动成功", 0);
        }
        protected void ParseMessage(Connection con, ProtocolBase protocol)
        {
            if (_battleEnd == true)
            {
                return;
            }

            MessageType messageType = (MessageType)protocol.getByte();

            switch (messageType)
            {
            case MessageType.Frame:
                byte   clientId = protocol.getByte();
                byte[] t2       = protocol.getLastBytes();
                StepMessage[con.clientId] = t2;
                ClientPool[clientId].SetActive();
                ServerLog.LogClient("Key:[" + t2.Length + "]", 3, clientId);
                break;

            case MessageType.ClientReady:
                break;

            case MessageType.Ping:
                byte id = protocol.getByte();
                SendPingToClient(id);
                break;

            default:
                Console.WriteLine("not handle messagetype " + messageType);
                return;
            }

            if (protocol.Length > 0)
            {
                ServerLog.LogServer("剩余未解析" + protocol.Length, 1);
            }
        }
        protected void SendStepAll(object sender, ElapsedEventArgs e)
        {
            _durationTime += 100;
            if (_durationTime >= 20000)
            {
                //_battleEnd = true;
            }

            if (ClientPool.ActiveCount <= 0)
            {
                if (FrameList.Count > 0)
                {
                    ServerLog.LogServer("所有客户端退出游戏 战斗结束!!!", 1);
                    FrameList.Clear();
                }
                return;
            }

            if (FrameList.Count == 0)
            {
                ServerLog.LogServer("玩家进入服务器 战斗开始!!!", 1);
            }

            ServerLog.LogServer("0[" + FrameList.Count + "]", 1);

            byte[][]     temp     = StepMessage;
            int          length   = temp.Length;
            ProtocolBase protocol = new ByteProtocol();

            protocol.push((byte)MessageType.Frame);
            protocol.push((byte)length);
            //ServerLog.LogServer("获取[" + FrameList.Count + "]", 1);
            for (int i = 0; i < length; i++)
            {
                protocol.push(temp[i] != null);
                protocol.push(temp[i]);
            }

            if (FrameList.Count == 0)
            {
                protocol.push((byte)MessageType.RandomSeed);
                Random rand = new Random();
                protocol.push(rand.Next(10000));
            }

            if (_battleEnd == true)
            {
                protocol.push((byte)MessageType.BattleEnd);
            }

            protocol.push((byte)MessageType.end);
            ServerLog.LogServer("生成帧信息[" + length + "]", 1);
            byte[] temp2 = protocol.GetByteStream();

            FrameList.Add(temp2);

            ClientPool.Foreach((con) =>
            {
                SendToClient(con.clientId, temp2);
                if (!con.ActiveCheck())
                {
                    ServerLog.LogClient("客户端断线 中止连接:" + ClientPool[con.clientId].socket.LocalEndPoint + "ClientID:" + con.clientId, 0, con.clientId);
                    con.socket.Close();
                    ClientPool.Recover(con.clientId);
                }
            });

            if (_battleEnd == true)
            {
                ClientPool.Foreach((con) =>
                {
                    con.socket.Close();
                    ClientPool.Recover(con.clientId);
                });
            }

            ServerLog.LogServer("帧同步[" + FrameList.Count + "]", 2);
        }