Example #1
0
        public PlayerServer CreateNewPlayer()
        {
            //Assign id based on the next spot in the gameObjectDict.
            int id = gameObjectDict.Count();

            //Create two players, one to send as an active player to client. Other to keep track of on server.
            PlayerServer newPlayer = matchHandler.AddPlayer();

            newPlayer.Register();
            playerServerList.Add(newPlayer);

            //Create the active player with the same id as the newPlayer.
            PlayerServer newActivePlayer = new PlayerServer(newPlayer.Team)
            {
                ObjectType = ObjectType.ACTIVE_PLAYER,
                Id         = newPlayer.Id
            };

            newActivePlayer.Transform.Position = newPlayer.Transform.Position;

            CreatePlayerPacket objPacket = (CreatePlayerPacket)ServerPacketFactory.NewCreatePacket(newPlayer);

            // Sending this new packet before the new client joins.
            networkServer.SendAll(PacketUtil.Serialize(objPacket));

            return(newActivePlayer);
        }
Example #2
0
        public void SendWorldUpdateToAllClients()
        {
            List <GameObjectServer> gameObjects = GameServer.instance.GetInteractableObjects();

            List <byte> allPackets = new List <byte>();

            for (int i = 0; i < gameObjects.Count; i++)
            {
                GameObjectServer objectToSend = gameObjects[i];

                //Send an update if the object is not a leaf or if the leaf has been modified.
                if ((objectToSend is LeafServer && objectToSend.Modified) || (objectToSend is PlayerServer))
                {
                    objectToSend.Modified = false;
                    BasePacket packetToSend = ServerPacketFactory.CreateUpdatePacket(gameObjects[i]);
                    allPackets.AddRange(PacketUtil.Serialize(packetToSend));
                }
            }

            SendAll(allPackets.ToArray());
            List <byte> destroyPackets = new List <byte>();

            lock (GameServer.instance.toDestroyQueue)
            {
                foreach (var gameObj in GameServer.instance.toDestroyQueue)
                {
                    BasePacket packet = PacketFactory.NewDestroyPacket(gameObj);
                    destroyPackets.AddRange(PacketUtil.Serialize(packet));
                }
            }

            SendAll(destroyPackets.ToArray());
        }
Example #3
0
    public sbyte ReadSbyte()
    {
        byte[] data = this._buffer.GetRange(this._offset, 1).ToArray();
        this._offset += 1;

        return(PacketUtil.ReadSbyte(data));
    }
Example #4
0
        /**
         * --------------------------------------------------------------
         * |					IMU UDP PACKET                          |
         * --------------------------------------------------------------
         * |  char		| prefix			|	5 bytes	|	0	|	5	|
         * |			| STRUCT PADDING	|   3 bytes	|	5	|   8	|
         * |  f32		| avg_x				|	4 bytes	|	8	|	12	|
         * |  f32		| max_x				|	4 bytes	|	12	|	16	|
         * |  f32		| min_x				|	4 bytes	|	16	|	20	|
         * |  f32		| avg_y				|	4 bytes	|	20	|	24	|
         * |  f32		| max_y				|	4 bytes	|	24	|	28	|
         * |  f32		| min_y				|	4 bytes	|	28	|	32	|
         * |  f32		| avg_z				|	4 bytes	|	32	|	36	|
         * |  f32		| max_z				|	4 bytes	|	36	|	40	|
         * |  f32		| min_z				|	4 bytes	|	40	|	44	|
         * |  f32		| angle_x			|	4 bytes	|	44	|	48	|
         * |  f32		| angle_y			|	4 bytes	|	48	|	52	|
         * |  f32		| angle_z			|	4 bytes	|	52	|	56	|
         * --------------------------------------------------------------
         */
        public void ConvertBytesToOBj(byte[] packet)
        {
            // x
            float avg = BitConverter.ToSingle(PacketUtil.GetBytes(packet, 8, 12), 0);
            float max = BitConverter.ToSingle(PacketUtil.GetBytes(packet, 12, 16), 0);
            float min = BitConverter.ToSingle(PacketUtil.GetBytes(packet, 16, 20), 0);

            this.x = new Statistic(avg, max, min);

            // y
            avg = BitConverter.ToSingle(PacketUtil.GetBytes(packet, 20, 24), 0);
            max = BitConverter.ToSingle(PacketUtil.GetBytes(packet, 24, 28), 0);
            min = BitConverter.ToSingle(PacketUtil.GetBytes(packet, 28, 32), 0);

            this.y = new Statistic(avg, max, min);

            // z
            avg = BitConverter.ToSingle(PacketUtil.GetBytes(packet, 32, 36), 0);
            max = BitConverter.ToSingle(PacketUtil.GetBytes(packet, 36, 40), 0);
            min = BitConverter.ToSingle(PacketUtil.GetBytes(packet, 40, 44), 0);

            this.z = new Statistic(avg, max, min);

            // angle

            float angle_x = BitConverter.ToSingle(PacketUtil.GetBytes(packet, 44, 48), 0);
            float angle_y = BitConverter.ToSingle(PacketUtil.GetBytes(packet, 48, 52), 0);
            float angle_z = BitConverter.ToSingle(PacketUtil.GetBytes(packet, 52, 56), 0);

            this.angle = new Vector3f(angle_x, angle_y, angle_z);
        }
Example #5
0
    public short ReadShort()
    {
        byte[] data = this._buffer.GetRange(this._offset, 2).ToArray();
        this._offset += 2;

        return(PacketUtil.ReadShort(data));
    }
Example #6
0
        /// <summary>
        /// Receives bytes from the ByteReceivedQueue and deserializes them into packets for later processing.
        /// </summary>
        public void Receive()
        {
            while (ByteReceivedQueue.Count > 0)
            {
                // If there is not enough data left to read the size of the next packet, do other game updates
                if (ByteReceivedQueue.Count < PacketUtil.PACK_HEAD_SIZE)
                {
                    break;
                }

                // Get packet size
                byte[] headerByteBuf = ByteReceivedQueue.GetRange(0, PacketUtil.PACK_HEAD_SIZE).ToArray();
                int    packetSize    = BitConverter.ToInt32(headerByteBuf, 1);

                // If there is not enough data left to read the next packet, do other game updates
                if (ByteReceivedQueue.Count < packetSize + PacketUtil.PACK_HEAD_SIZE)
                {
                    break;
                }

                // Get full packet and add it to the queue
                byte[]     packetData = ByteReceivedQueue.GetRange(PacketUtil.PACK_HEAD_SIZE, packetSize).ToArray();
                byte[]     fullPacket = headerByteBuf.Concat(packetData).ToArray();
                BasePacket packet     = PacketUtil.Deserialize(fullPacket);
                PacketQueue.Add(packet);

                // Remove the read data
                lock (ByteReceivedQueue)
                {
                    ByteReceivedQueue.RemoveRange(0, packetSize + PacketUtil.PACK_HEAD_SIZE);
                }
            }
        }
Example #7
0
        public void Execute(PacketBodyBase requestPacketBody, ReceivedSocketState receivedSocketState)
        {
            LoginResponse _response  = null;
            string        _exception = string.Empty;

            try
            {
                var _request = (LoginRequest)requestPacketBody;
                _response = this.CheckLogin(_request);
            }
            catch (Exception ex)
            {
                _response = new LoginResponse
                {
                    Status  = false,
                    Message = ResponseMessage.COMM_NETWORK_ERROR,
                };
                _exception = ex.ToString();
            }

            try
            {
                receivedSocketState.Response(PacketUtil.Pack(_response));
                Logger.LogInfo(string.Format("收到来自{0}的请求,Request = {1},Response = {2},Exception = {3}"
                                             , receivedSocketState.ClientIpAddress, requestPacketBody.ToString(), _response.ToString(), _exception));
            }
            catch (Exception ex)
            {
                throw new ResponseException(ex.ToString());
            }
        }
Example #8
0
 void PacketInterface.Encode()
 {
     PacketUtil.EncodeHeader(Packet_, GetType());
     PacketUtil.Encode(Packet_, client_id_);
     PacketUtil.Encode(Packet_, id_);
     PacketUtil.Encode(Packet_, result_);
 }
Example #9
0
        /// <summary>
        /// Initializes the match handler.
        /// </summary>
        public MatchHandler(Match toHandle, NetworkServer networkHandler, GameServer game)
        {
            if (instance != null)
            {
                Console.WriteLine("DOUBLE INSTANTIATING MATCH HANDLER!");
            }

            instance = this;

            match           = toHandle;
            network         = networkHandler;
            this.game       = game;
            matchResetTimer = new Stopwatch();
            statsTimer      = new Timer
            {
                AutoReset = true,
                Interval  = 1000
            };
            statsTimer.Elapsed += (sender, args) =>
            {
                foreach (PlayerServer player in GameServer.instance.playerServerList)
                {
                    network.SendAll(PacketUtil.Serialize(new StatResultPacket(player.playerStats, player.Id)));
                }
            };
        }
Example #10
0
        public void ConvertBytesObjSmallIncrements(byte[] packet)
        {
            // First get the prefix
            string prefix = Encoding.ASCII.GetString(PacketUtil.GetBytes(packet, 0, 7)).Substring(0, 5);

            if (totalCounter == 1)
            {
                this.totalCounter = 0;
                this.increment    = new int[3];
                this.counter      = new int[3];
            }

            if (prefix == "FFTx,")
            {
                //Console.WriteLine("Got new FFT X Packet => Total: {0} Counter: {1} {2} {3} Increment: {4} {5} {6}",
                //    totalCounter.ToString(), this.counter[0], this.counter[1], this.counter[2], this.increment[0], this.increment[1], this.increment[2]);
                this.counter[0]++;
            }
            else if (prefix == "FFTy,")
            {
                //Console.WriteLine("Got new FFT Y Packet => Total: {0} Counter: {1} {2} {3} Increment: {4} {5} {6}",
                //    totalCounter.ToString(), this.counter[0], this.counter[1], this.counter[2], this.increment[0], this.increment[1], this.increment[2]);
                this.counter[1]++;
            }
            else if (prefix == "FFTz,")
            {
                //Console.WriteLine("Got new FFT Z Packet => Total: {0} Counter: {1} {2} {3} Increment: {4} {5} {6}",
                //    totalCounter.ToString(), this.counter[0], this.counter[1], this.counter[2], this.increment[0], this.increment[1], this.increment[2]);
                this.counter[2]++;
            }

            int max = (8 + (this.N * 4)) - 1;

            for (int i = 8; i < max; i += 4)
            {
                if (prefix == "FFTx,")
                {
                    byte[] section = PacketUtil.GetBytes(packet, i, i + 4);
                    float  value   = BitConverter.ToSingle(section, 0);
                    this.Out[increment[0]].x = value;
                    this.increment[0]++;
                }
                else if (prefix == "FFTy,")
                {
                    byte[] section = PacketUtil.GetBytes(packet, i, i + 4);
                    float  value   = BitConverter.ToSingle(section, 0);
                    this.Out[increment[1]].y = value;
                    this.increment[1]++;
                }
                else if (prefix == "FFTz,")
                {
                    byte[] section = PacketUtil.GetBytes(packet, i, i + 4);
                    float  value   = BitConverter.ToSingle(section, 0);
                    this.Out[increment[2]].z = value;
                    this.increment[2]++;
                }
            }
            this.totalCounter++;
        }
Example #11
0
        /// <summary>
        /// 解析支付平台发送给商户平台的交易通知请求
        /// </summary>
        /// <param name="pCerFilePath">cer证书文件的路径</param>
        /// <param name="pEncryptedContent">支付平台发送过来的加密后的密文</param>
        /// <returns></returns>
        public static TransactionNotificationRequest ParseTransactionNotificationRequest(string pCerFilePath, string pEncryptedContent)
        {
            string decryptedContent            = PacketUtil.ParseRequestPackets(pCerFilePath, pEncryptedContent);
            TransactionNotificationRequest req = new TransactionNotificationRequest();

            req.Load(decryptedContent);
            return(req);
        }
Example #12
0
        /// <summary>
        /// Starts the match and sends an update to all clients
        /// </summary>
        /// <param name="time">The time of match duration</param>
        public void StartMatch()
        {
            match.StartMatch(Constants.MATCH_TIME);
            network.SendAll(PacketUtil.Serialize(new MatchStartPacket(Constants.MATCH_TIME)));

            statsTimer.Enabled = true;
            statsTimer.Start();
        }
Example #13
0
    private static void HandleClient(object obSocket)
    {
        Socket clientSocket = (Socket)obSocket;

        ushort lenHeader  = 2;
        uint   lenMaxBuff = 51200;
        ushort lenTmpBuff = 512;

        byte[] buffers    = new byte[lenMaxBuff];
        byte[] buffersTmp = new byte[lenTmpBuff];
        int    buffersLen = 0;

        while (true)
        {
            int readCount = clientSocket.Receive(buffersTmp, lenTmpBuff, 0);

            if (readCount == 0)
            {
                break;
            }

            Array.Copy(buffersTmp, 0, buffers, buffersLen, readCount);
            buffersLen += readCount;

            if (buffersLen <= lenHeader)
            {
                continue;
            }

            while (true)
            {
                ushort packageCount = PacketUtil.ReadUshort(buffers);

                if (buffersLen < packageCount + lenHeader)
                {
                    break;
                }

                buffersLen -= packageCount + lenHeader;

                byte[] buffPid = new byte[2];
                byte[] buff    = new byte[packageCount];

                Array.Copy(buffers, 2, buffPid, 0, 2);
                Array.Copy(buffers, 4, buff, 0, packageCount - 2);
                Array.Copy(buffers, packageCount + 2, buffers, 0, buffersLen);

                ushort packetId = PacketUtil.ReadUshort(buffPid);

                Packet packet = new Packet(buff);

                DoMsg(clientSocket, packetId, packet);
            }
        }

        clientSocket.Shutdown(SocketShutdown.Both);
        clientSocket.Close();
    }
Example #14
0
    public string ReadString()
    {
        ushort len = this.ReadUshort();

        byte[] data = this._buffer.GetRange(this._offset, len).ToArray();
        this._offset += len;

        return(PacketUtil.ReadString(data));
    }
Example #15
0
    private void run()
    {
        byte[] read_buffer     = new byte[this._max_buff_len];
        int    read_buffer_len = 0;

        while (true)
        {
            if (this._socket != null)
            {
                byte[] temp      = new byte[this._temp_buff_len];
                int    readCount = this._socket.Receive(temp, this._temp_buff_len, 0);
                if (readCount == 0)
                {
                    Log.Error("NetReceive readCount is 0");
                    this.OnDisconnect();
                    continue;
                }

                Array.Copy(temp, 0, read_buffer, read_buffer_len, readCount);
                read_buffer_len += readCount;

                if (read_buffer_len <= this._len_header)
                {
                    continue;
                }

                while (true)
                {
                    ushort package_count = PacketUtil.ReadUshort(read_buffer);

                    if (read_buffer_len < package_count + this._len_header)
                    {
                        break;
                    }

                    read_buffer_len -= package_count + this._len_header;

                    byte[] buf = new byte[package_count];

                    Array.Copy(read_buffer, this._len_header, buf, 0, package_count);

                    Array.Copy(read_buffer, package_count + this._len_header, read_buffer, 0, read_buffer_len);


                    Packet packet = new Packet(buf);

                    lock (this._queue)
                    {
                        this._queue.Enqueue(packet);
                    }
                }
            }
            Thread.Sleep(100);
        }
    }
Example #16
0
    public void Encode(ushort packetId)
    {
        List <byte> all = new List <byte>();

        // 包体总长度 = (协议内容长度 + 协议号长度)
        PacketUtil.WriteUshort(all, (ushort)(this._buffer.Count + 2));
        PacketUtil.WriteUshort(all, packetId);
        all.AddRange(this._buffer);

        this._buffer = all;
    }
Example #17
0
        public void ConvertBytesObj(byte[] packet)
        {
            // First get the prefix
            string prefix = Encoding.ASCII.GetString(PacketUtil.GetBytes(packet, 0, 7)).Substring(0, 5);

            // When you enter this reset everything
            if (this.totalCounter == 8)
            {
                this.Out          = new Vector3f[this.N];
                this.totalCounter = 0;
                this.increment    = new int[3];
                this.counter      = new int[3];
            }

            //
            for (int i = 0; i < increment.Length; i++)
            {
                increment[i] = 0 + (this.counter[i] * 250);
            }

            if (prefix == "FFTx,")
            {
                Console.WriteLine("Got new FFT X Packet => {0} ", totalCounter.ToString());
                this.counter[0]++;
            }
            else if (prefix == "FFTy,")
            {
                Console.WriteLine("Got new FFT Y Packet => {0} ", totalCounter.ToString());
                this.counter[1]++;
            }

            // Filling the array
            const int max = (8 + (250 * 4)) - 1;

            for (int i = 8; i < max; i += 4)
            {
                if (prefix == "FFTx,")
                {
                    this.Out[increment[0]].x = BitConverter.ToSingle(PacketUtil.GetBytes(packet, i, i + 4), 0);
                    this.increment[0]++;
                }
                else if (prefix == "FFTy,")
                {
                    this.Out[increment[1]].y = BitConverter.ToSingle(PacketUtil.GetBytes(packet, i, i + 4), 0);
                    this.increment[1]++;
                }
                //else if (prefix == "FFTz,")
                //{
                //    //this.Out[increment[2]].z = BitConverter.ToSingle(PacketUtil.GetBytes(packet, i, i + 4), 0);
                //    increment[2]++;
                //}
            }
            this.totalCounter++;
        }
Example #18
0
        public void TestParseRequestPackets()
        {
            string encrypedReq1 = null;

            using (var s = ReflectionUtils.GetEmbeddedResource("JIT.TestUtility.TestPay.TestMaterial.notification_req1.txt"))
            {
                TextReader reader = new StreamReader(s);
                encrypedReq1 = reader.ReadToEnd();
            }
            string req1 = PacketUtil.ParseRequestPackets("D:/cer/5101200070003100001.cer", encrypedReq1);
        }
Example #19
0
    public static string ReadFixedString(BinaryReader iStream, Int32 size)
    {
        string tmp = PacketUtil.ReadString(iStream, size);
        //处理服务器发来的不正常数据
        int nTmp = tmp.IndexOf("\0");

        if (nTmp > -1)
        {
            tmp = tmp.Substring(0, nTmp);
        }
        return(tmp);
    }
Example #20
0
        public void Run()
        {
            try
            {
                //create an UDTServerSocket on a free port
                UDTServerSocket server = new UDTServerSocket(0);
                // do hole punching to allow the client to connect
                IPAddress  clientAddress = IPAddress.Parse(clientIP);
                IPEndPoint point         = new IPEndPoint(clientAddress, clientPort);
                //发送一字节确认端口
                Util.DoHolePunch(server.getEndpoint(), point);
                int localPort = server.getEndpoint().LocalPort; //获取真实端口
                                                                //output client port
                writeToOut("OUT: " + localPort);

                //now start the send...
                UDTSocket       socket    = server.Accept();
                UDTOutputStream outStream = socket.GetOutputStream();
                FileInfo        file      = new FileInfo(localFilename);
                if (!file.Exists)
                {
                    Console.WriteLine("没有文件:" + localFilename);
                    socket.Close();
                    server.ShutDown();
                    return;
                }
                FileStream fis = new FileStream(localFilename, FileMode.Open);
                try
                {
                    //send file size info
                    long size = fis.Length;
                    PacketUtil.Encode(size);
                    outStream.Write(PacketUtil.Encode(size));
                    long start = DateTime.Now.Ticks;
                    //and send the file
                    Util.CopyFileSender(fis, outStream, size, false);
                    long end = DateTime.Now.Ticks;
                    Console.WriteLine(socket.GetSession().Statistics);
                    float mbRate   = 1000 * size / 1024 / 1024 / (end - start);
                    float mbitRate = 8 * mbRate;
                    Console.WriteLine("Rate: " + (int)mbRate + " MBytes/sec. " + mbitRate + " mbit/sec.");
                }
                finally
                {
                    fis.Close();
                    socket.Close();
                }
            }
            catch (Exception ex)
            {
            }
        }
Example #21
0
        /// <summary>
        /// ---------------------------------------------
        /// |        IMU DATA UDP PACKET                |
        /// ---------------------------------------------
        /// | f32 | Ax		    | 4 bytes | 0   | 4     |
        /// | f32 | Ay		    | 4 bytes | 4   | 8     |
        /// | f32 | Az		    | 4 bytes | 8   | 12    |
        /// | f32 | Gz		    | 4 bytes | 12  | 16    |
        /// | f32 | Gy		    | 4 bytes | 16  | 20    |
        /// | f32 | Gz		    | 4 bytes | 20  | 24    |
        /// | f32 | AngleX	    | 4 bytes | 24  | 28    |
        /// | f32 | AngleY	    | 4 bytes | 28  | 32    |
        /// | f32 | AngleZ	    | 4 bytes | 32  | 36    |
        /// | f32 | CompAngleX	| 4 bytes | 40  | 44    |
        /// | f32 | CompAngleY	| 4 bytes | 44  | 48    |
        /// | f32 | CompAngleZ	| 4 bytes | 48  | 52    |
        /// ---------------------------------------------
        /// </summary>
        public void ConvertBytesToObj(byte[] packet)
        {
            this.ax = BitConverter.ToSingle(PacketUtil.GetBytes(packet, 0, 4), 0);
            this.ay = BitConverter.ToSingle(PacketUtil.GetBytes(packet, 4, 8), 0);
            this.az = BitConverter.ToSingle(PacketUtil.GetBytes(packet, 8, 12), 0);
            this.gx = BitConverter.ToSingle(PacketUtil.GetBytes(packet, 12, 16), 0);
            this.gy = BitConverter.ToSingle(PacketUtil.GetBytes(packet, 16, 20), 0);
            this.gz = BitConverter.ToSingle(PacketUtil.GetBytes(packet, 20, 24), 0);

            this.angle.x = BitConverter.ToSingle(PacketUtil.GetBytes(packet, 24, 28), 0);
            this.angle.y = BitConverter.ToSingle(PacketUtil.GetBytes(packet, 28, 32), 0);
            this.angle.z = BitConverter.ToSingle(PacketUtil.GetBytes(packet, 32, 36), 0);
        }
Example #22
0
        /// <summary>
        /// Sends all the game objects that exist within the game world to
        /// a client
        /// </summary>
        /// <param name="clientSocket">
        /// The client to send all the game objects in the world to
        /// </param>
        private void SendWorldToClient(Socket clientSocket)
        {
            List <byte>             allWorldPackets = new List <byte>();
            List <GameObjectServer> world           = GameServer.instance.GetGameObjectList();

            foreach (GameObjectServer val in world)
            {
                BasePacket packetToSend = ServerPacketFactory.NewCreatePacket(val);
                allWorldPackets.AddRange(PacketUtil.Serialize(packetToSend));
            }

            clientSocket.Send(allWorldPackets.ToArray());
        }
Example #23
0
 public T Send <T>(PacketBodyBase packageBody) where T : PacketBodyBase
 {
     try
     {
         var _data          = PacketUtil.Pack(packageBody);
         var _bytesReceived = this.SocketSender.Send(_data);
         var _packageBody   = PacketUtil.UnPackResponse(_bytesReceived);
         return((T)_packageBody);
     }
     catch
     {
         throw;
     }
 }
Example #24
0
        /// <summary>
        /// Ends the match by sending out a match result packet and burning all the leaves, starting a reset timer
        /// </summary>
        /// <param name="winningTeam">The team that won the match</param>
        private void EndMatch(Team winningTeam)
        {
            GameResultPacket donePacket = new GameResultPacket(winningTeam.name);

            network.SendAll(PacketUtil.Serialize(donePacket));

            foreach (PlayerServer player in GameServer.instance.playerServerList)
            {
                network.SendAll(PacketUtil.Serialize(new StatResultPacket(player.playerStats, player.Id)));
            }

            game.GetLeafListAsObjects().ForEach(l => { l.Burning = true; });
            match.StopMatch();
            matchResetTimer.Start();
        }
        internal override void Send(Packet packet, GProtocolSendType type, bool canSendBigSize = false,
                                    bool isCritical = false, bool isEvent = false)
        {
            try
            {
                if (IsConnected())
                {
                    packet.SendType = type;
                    var buffer = PacketSerializable.Serialize(packet, null, false);

                    if (!canSendBigSize && !PacketUtil.CheckPacketSize(buffer))
                    {
                        throw new GameServiceException("this Packet Is Too Big!,Max Packet Size is " +
                                                       RealTimeConst.MaxPacketSize + " bytes.")
                              .LogException <GsUdpClient>(DebugLocation.RealTime, "Send");
                    }

                    switch (type)
                    {
                    case GProtocolSendType.UnReliable:
                        Client?.SendUnReliable(buffer);
                        break;

                    case GProtocolSendType.Reliable:
                        if (isCritical)
                        {
                            Client?.SendCommand(buffer);
                        }
                        else
                        {
                            Client?.SendReliable(buffer, isEvent);
                        }
                        break;

                    default:
                        throw new ArgumentOutOfRangeException(nameof(type), type, null);
                    }
                }
                else
                {
                    DebugUtil.LogError <GsUdpClient>(DebugLocation.RealTime, "Send", "Client not Connected!");
                }
            }
            catch (Exception e)
            {
                e.LogException <GsUdpClient>(DebugLocation.RealTime, "Send");
            }
        }
Example #26
0
        public void TestPacketUtil()
        {
            string       _publicKey = SecurityHelper.GetRsaPublicKey();
            LoginRequest _request   = new LoginRequest();

            _request.LoginName = "Albin";
            _request.LoginPwd  = "123456";

            var _bytes      = PacketUtil.Pack(_request);
            var _packetBody = PacketUtil.UnPackRequest(_bytes);

            string _expected = _request.ToString()
            , _actual        = _packetBody.ToString();

            Assert.AreEqual(_expected, _actual, string.Format("数据包打包、解包失败,打包前是:{0},打包、解包后是:{1}", _expected, _actual));
        }
Example #27
0
        /// <summary>
        /// Creates a new player in the game, sends it out to all the clients,
        /// and then sends that active player to the clientSocket that is
        /// specified
        /// </summary>
        /// <param name="clientSocket">
        /// The socket that needs an active player
        /// </param>
        private void ProcessNewPlayer(Socket clientSocket)
        {
            PlayerServer player = GameServer.instance.CreateNewPlayer();

            //Associate player's id with with the socket.
            playerDictionary.Add(clientSocket, player.Id);

            BasePacket createPlayPack = ServerPacketFactory.NewCreatePacket(player);

            // Create createObjectPacket, send to client
            byte[] data = PacketUtil.Serialize(createPlayPack);
            Send(clientSocket, data);
            MatchStartPacket informStart =
                new MatchStartPacket(MatchHandler.instance.GetMatch().GetTimeElapsed().Milliseconds);

            Send(clientSocket, PacketUtil.Serialize(informStart));
        }
Example #28
0
        /// <summary>
        /// Connect to a requesting socket.
        /// </summary>
        /// <param name="ar">Stores socket and buffer data</param>
        public void AcceptCallback(IAsyncResult ar)
        {
            // Signal the main thread to continue.
            allDone.Set();

            // Get the socket that handles the client request.
            Socket listener     = (Socket)ar.AsyncState;
            Socket clientSocket = listener.EndAccept(ar);

            if (MatchHandler.instance.GetMatch().Started())
            {
                //Sending match time first so it's processed first.
                MatchStartPacket informStart =
                    new MatchStartPacket((float)(Constants.MATCH_TIME -
                                                 MatchHandler.instance.GetMatch().GetTimeElapsed().TotalSeconds));
                Send(clientSocket, PacketUtil.Serialize(informStart));
            }

            // Create a new player and send them the world
            SendWorldToClient(clientSocket);
            if (GameServer.instance.playerServerList.Count < Constants.NUM_PLAYERS)
            {
                ProcessNewPlayer(clientSocket);
            }
            else
            {
                SendSpectator(clientSocket);
            }

            // Add the new socket to the list of sockets recieving updates
            clientSockets.Add(clientSocket);

            GameServer.instance.ConnectCallback();
            // Create the state object.
            StateObject state = new StateObject();

            state.workSocket = clientSocket;
            clientSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                      new AsyncCallback(ReceiveCallback), state);

            //Start listening for the next connection
            listener.BeginAccept(
                new AsyncCallback(AcceptCallback),
                listener);
        }
Example #29
0
    public static void Write(BinaryWriter oStream, string value, bool addLength = true)
    {
        if (oStream == null)
        {
            return;
        }

        Int32 strLength = PacketUtil.GetUTF8StringLength(value);

        if (addLength)
        {
            oStream.Write(strLength);
        }

        if (strLength > 0)
        {
            PacketUtil.WriteString(oStream, value);
        }
    }
Example #30
0
        /// <summary>
        /// Sends out the data associated with the active player's input if the player is requesting something different,
        /// resets requested movement.
        ///
        /// </summary>
        private void SendRequest()
        {
            // Create a new player packet, and fill it with player info.
            RequestPacket toSend =
                ClientPacketFactory.CreateRequestPacket(ActivePlayer);

            //If this is sending different data from before, send it.
            if (!RequestPacket.equals(toSend, lastRequest))
            {
                byte[] data = PacketUtil.Serialize(toSend);
                networkClient.Send(data);

                lastRequest = toSend;
            }

            // Reset the player's requested movement after the packet is sent.
            // Note: This should be last!
            ActivePlayer.ResetRequests();
        }