public G9SendAndReceivePacket(G9PacketType typeOfPacket, G9PacketDataType packetDataType, string command,
                                      byte[] oBody, Guid requestId)
#endif
        {
            PacketType     = typeOfPacket;
            PacketDataType = packetDataType;
            Command        = command;
#if NETSTANDARD2_1 || NETCOREAPP3_0 || NETCOREAPP3_1
            Body = oBody.ToArray();
#else
            Body = oBody;
#endif
            RequestId = requestId;
        }
Exemple #2
0
        /// <summary>
        ///     <para>Send command request by name</para>
        ///     <para>With custom packet data type</para>
        /// </summary>
        /// <param name="commandName">Name of command</param>
        /// <param name="commandData">Data for send</param>
        /// <param name="packetDataType">custom packet data type</param>
        /// <param name="customRequestId">send data by custom request id</param>
        /// <param name="checkCommandExists">
        ///     <para>If set true, check command exists</para>
        ///     <para>If not exists throw exception</para>
        /// </param>
        /// <param name="checkCommandSendType">
        ///     <para>If set true, check command send type</para>
        ///     <para>If func send data type not equal with command send type throw exception</para>
        /// </param>

        #region SendCommandByNameWithCustomPacketDataType

        private void SendCommandByNameWithCustomPacketDataType(string commandName, object commandData,
                                                               G9PacketDataType packetDataType, Guid?customRequestId = null,
                                                               bool checkCommandExists = true, bool checkCommandSendType = true)
        {
            try
            {
                // Check exists command
                if (checkCommandExists && !_commandHandler.CheckCommandExist(commandName))
                {
                    throw new Exception($"{LogMessage.Command}\n{LogMessage.CommandName}: {commandName}");
                }

                // Check exists command
                if (checkCommandSendType &&
                    _commandHandler.GetCommandSendType(commandName) != commandData.GetType())
                {
                    throw new Exception(
                              $"{LogMessage.CommandSendTypeNotCorrect}\n{LogMessage.CommandName}: {commandName}\n{LogMessage.SendTypeWithFunction}: {commandData.GetType()}\n{LogMessage.CommandSendType}: {_commandHandler.GetCommandSendType(commandName)}");
                }

                // Ready data for send
                var dataForSend = ReadyDataForSend(commandName, commandData, packetDataType, customRequestId);

                // Get total packets
                var packets = dataForSend.GetPacketsArray();

                // Send total packets
                for (var i = 0; i < dataForSend.TotalPackets; i++)
                {
                    // Try to send
                    Send(_clientSocket, packets[i])?.WaitOne(3999);
                }
            }
            catch (Exception ex)
            {
                // Set log
                if (_logging.CheckLoggingIsActive(LogsType.EXCEPTION))
                {
                    _logging.LogException(ex, LogMessage.FailSendComandByNameAsync,
                                          G9LogIdentity.CLIENT_SEND_DATA, LogMessage.FailedOperation);
                }

                // Run event on error
                OnErrorHandler(ex, ClientErrorReason.ErrorReadyToSendDataToServer);
            }
        }
        /// <summary>
        ///     Constructor
        ///     Initialize Requirement
        /// </summary>
        /// <param name="typeOfPacket">Specify type of packet</param>
        /// <param name="packetDataType">Specified packet data type</param>
        /// <param name="command">Specify command</param>
        /// <param name="oBody">Specify packet body</param>
        /// <param name="requestId">Specify unique request id</param>

        #region G9SendAndReceivePackage

#if NETSTANDARD2_1 || NETCOREAPP3_0 || NETCOREAPP3_1
        public G9SendAndReceivePacket(G9PacketType typeOfPacket, G9PacketDataType packetDataType, string command,
                                      ReadOnlySpan <byte> oBody, Guid requestId)
        public G9PacketSplitHandler PackingRequestByData(byte[] command, byte[] body,
                                                         G9PacketDataType dataType, Guid?customRequestId)
#endif
        {
            try
            {
                if (command.Length == CalculateCommandSize)
                {
                    var requestId      = customRequestId ?? Guid.NewGuid();
                    var requestIdBytes = requestId.ToByteArray();
                    G9PacketSplitHandler packet;
                    if (body.Length <= CalculateBodySize)
                    {
                        // Initialize packet split handler
                        packet = new G9PacketSplitHandler(requestId, 1);

                        // Initialize memory stream and save packet data
                        using (var memoryStream = new MemoryStream())
                        {
                            memoryStream.WriteByte((byte)G9PacketType.OnePacket);
                            memoryStream.WriteByte((byte)dataType);
                            memoryStream.WriteByte(checked ((byte)body.Length));
#if NETSTANDARD2_1 || NETCOREAPP3_0 || NETCOREAPP3_1
                            memoryStream.Write(command);
                            memoryStream.Write(body);
                            memoryStream.Write(requestIdBytes);
#else
                            memoryStream.Write(command, 0, command.Length);
                            memoryStream.Write(body, 0, body.Length);
                            memoryStream.Write(requestIdBytes, 0, requestIdBytes.Length);
#endif

                            // Add packet
                            packet.AddPacket(0, memoryStream.ToArray());
                        }
                    }
                    else
                    {
                        // Calculate packet size
                        var counter = (byte)Math.Ceiling(body.Length / (decimal)CalculateBodySize);

                        // Packet size plus one => because first packet specify packet count information
                        // counter.ToString().Length * counter => Reserve first byte for packet number
                        counter = (byte)(Math.Ceiling(((decimal)body.Length +
                                                       counter.ToString().Length *counter) /
                                                      CalculateBodySize) + 1);

                        // Specify counter length
                        // counter length = 1 => Like byte 0 To 256
                        var counterLength = 1;

                        // Initialize packet split
                        packet = new G9PacketSplitHandler(requestId, counter);

                        // Initialize memory stream and save packet data
                        using (var memoryStream = new MemoryStream())
                        {
                            memoryStream.WriteByte((byte)G9PacketType.MultiPacket);
                            memoryStream.WriteByte((byte)dataType);
                            // First packet length is 2 | 0 => packet number | 1 => Total packet count
                            memoryStream.WriteByte(2);
#if NETSTANDARD2_1 || NETCOREAPP3_0 || NETCOREAPP3_1
                            memoryStream.Write(command);
#else
                            memoryStream.Write(command, 0, command.Length);
#endif
                            // write packet number
                            memoryStream.WriteByte(0);
                            // write total packet count
                            memoryStream.WriteByte(counter);
#if NETSTANDARD2_1 || NETCOREAPP3_0 || NETCOREAPP3_1
                            memoryStream.Write(requestIdBytes);
#else
                            memoryStream.Write(requestIdBytes, 0, requestIdBytes.Length);
#endif

                            // Set first packet => packet count information
                            packet.AddPacket(0, memoryStream.ToArray());
                        }

                        for (byte i = 1; i < counter; i++)
                        {
                            var newBodyStandardSize = CalculateBodySize - (i == 1
                                                          ? 0
                                                          : counterLength);

                            var offset = newBodyStandardSize * i - newBodyStandardSize;

                            var length = i == counter - 1
                                ? body.Length - offset
                                : CalculateBodySize - counterLength;

                            // Initialize memory stream and save packet data
                            using (var memoryStream = new MemoryStream())
                            {
                                memoryStream.WriteByte((byte)G9PacketType.MultiPacket);
                                memoryStream.WriteByte((byte)dataType);
                                memoryStream.WriteByte(checked ((byte)(length + 1)));
#if NETSTANDARD2_1 || NETCOREAPP3_0 || NETCOREAPP3_1
                                memoryStream.Write(command);
#else
                                memoryStream.Write(command, 0, command.Length);
#endif
                                memoryStream.WriteByte(i);
#if NETSTANDARD2_1 || NETCOREAPP3_0 || NETCOREAPP3_1
                                memoryStream.Write(body.Slice(offset, length));
                                memoryStream.Write(requestId.ToByteArray());
#else
                                memoryStream.Write(body, offset, length);
                                memoryStream.Write(requestIdBytes, 0, requestIdBytes.Length);
#endif


                                // Add total packet
                                packet.AddPacket(i, memoryStream.ToArray());
                            }
                        }
                    }

                    return(packet);
                }

                if (_logging.CheckLoggingIsActive(LogsType.EXCEPTION))
                {
                    _logging.LogException(new ArgumentException(
                                              $"{LogMessage.CommandLengthError}\n{LogMessage.StandardLength}: {CalculateCommandSize}\n{LogMessage.LengthEntered}: {command.Length}"),
                                          null, G9LogIdentity.GENERATE_PACKET, LogMessage.FailedOperation);
                }

                return(null);
            }
            catch (Exception ex)
            {
                if (_logging.CheckLoggingIsActive(LogsType.EXCEPTION))
                {
                    _logging.LogException(ex, LogMessage.FailGeneratePacket, G9LogIdentity.GENERATE_PACKET,
                                          LogMessage.FailedOperation);
                }
                return(null);
            }
        }
        /// <summary>
        ///     <para>Generate and packing request by data</para>
        ///     <para>Perform calculations to prepare the request</para>
        /// </summary>
        /// <param name="command">Specify package command</param>
        /// <param name="body">Specify package body</param>
        /// <param name="dataType">Specified packet data type</param>
        /// <param name="customRequestId">Specified custom request id for send</param>
        /// <returns>Generated PacketSplitHandler by data</returns>

        #region PackingRequestByData

#if NETSTANDARD2_1 || NETCOREAPP3_0 || NETCOREAPP3_1
        public G9PacketSplitHandler PackingRequestByData(ReadOnlySpan <byte> command, ReadOnlySpan <byte> body,
                                                         G9PacketDataType dataType, Guid?customRequestId)
Exemple #6
0
        /// <summary>
        ///     Helper class for ready data for send
        /// </summary>
        /// <param name="commandName">Command name</param>
        /// <param name="data">Data for send</param>
        /// <param name="packetDataType">Custom packet data type</param>
        /// <param name="customRequestId">send data by custom request id</param>
        /// <returns>Ready packet split handler</returns>

        #region ReadyDataForSend

        private G9PacketSplitHandler ReadyDataForSend(string commandName, object data, G9PacketDataType packetDataType,
                                                      Guid?customRequestId)
        {
            // Ready data for send
#if NETSTANDARD2_1 || NETCOREAPP3_0 || NETCOREAPP3_1
            ReadOnlySpan <byte>
#else
            var
#endif
            dataForSend = data is byte[]
                    ? (byte[])data
                    : Configuration.EncodingAndDecoding.EncodingType.GetBytes(data.ToJson());

            // Initialize command - length = CommandSize
#if NETSTANDARD2_1 || NETCOREAPP3_0 || NETCOREAPP3_1
            ReadOnlySpan <byte>
#else
            var
#endif
            commandData =
                Configuration.EncodingAndDecoding.EncodingType.GetBytes(
                    commandName.GenerateStandardCommandName(_packetManagement.CalculateCommandSize));

            return(_packetManagement.PackingRequestByData(commandData, dataForSend, packetDataType, customRequestId));
        }