Beispiel #1
0
        /// <summary>
        /// Returns the serialisedbytes of the packet header appended by the serialised header size. This is required to rebuild the header on receive.
        /// </summary>
        /// <returns>The serialised header as byte[]</returns>
        public byte[] SerialiseHeader(SendReceiveOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options", "Provided SendReceiveOptions cannot be null.");
            }

            //We need to start of by serialising the header
            byte[] serialisedHeader;
            using (StreamSendWrapper sendWrapper = options.DataSerializer.SerialiseDataObject(packetHeader, options.DataProcessors, null))
                serialisedHeader = sendWrapper.ThreadSafeStream.ToArray(1);

            if (serialisedHeader.Length - 1 > byte.MaxValue)
            {
                throw new SerialisationException("Unable to send packet as header size is larger than Byte.MaxValue. Try reducing the length of provided packetTypeStr or turning off checkSum validation.");
            }

            //The first byte now specifies the header size (allows for variable header size)
            serialisedHeader[0] = (byte)(serialisedHeader.Length - 1);

            if (serialisedHeader == null)
            {
                throw new SerialisationException("Serialised header bytes should never be null.");
            }

            return(serialisedHeader);
        }
        // Methods
        #region FileSend
        void FileSend()
        {
            //This is our progress percent, between 0 and 1
            double progressPercentage = 0;

            //Initialise stream with 1MB
            byte[]           buffer         = new byte[1024 * 1024];
            ThreadSafeStream dataToSend     = new ThreadSafeStream(new System.IO.MemoryStream(buffer));
            long             totalBytesSent = 0;

            //We will send in chunks of 50KB
            int sendInChunksOfNBytes = 50 * 1024;

            //Get the connection to the target
            Connection connection = TCPConnection.GetConnection(new ConnectionInfo(this.serverIp, this.serverPort));

            do
            {
                //Determine the total number of bytes to send
                //We need to watch out for the end of the buffer when we send less than sendInChunksOfNBytes
                long bytesToSend = (buffer.Length - totalBytesSent > sendInChunksOfNBytes ? sendInChunksOfNBytes : buffer.Length - totalBytesSent);
                StreamSendWrapper streamWrapper = new StreamSendWrapper(dataToSend, totalBytesSent, bytesToSend);
                connection.SendObject("PartitionedSend", streamWrapper);
                totalBytesSent    += bytesToSend;
                progressPercentage = ((double)totalBytesSent / buffer.Length);
            }while (totalBytesSent < buffer.Length);
        }
 /// <summary>
 /// 傳送檔案
 /// </summary>
 /// <param name="Token">權杖</param>
 /// <param name="IPaddress">IP位址</param>
 /// <param name="Port">Port號</param>
 /// <param name="FilePath">檔案路徑</param>
 public void FileFunction(string Token, string IPaddress, int Port, string FilePath)
 {
     try
     {
         FileStream   fileStream   = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
         StreamReader streamReader = new StreamReader(fileStream);
         DataTable    dataTable    = new DataTable();
         bool         IsFirst      = true;
         string       strline      = null;
         while ((strline = streamReader.ReadLine()) != null)
         {
             if (IsFirst)
             {
                 try
                 {
                     ThreadSafeStream  threadSafeStream = new ThreadSafeStream(fileStream);
                     StreamSendWrapper sendWrapper      = new StreamSendWrapper(threadSafeStream, 0, fileStream.Length);
                     NetworkComms.SendObject(Token, IPaddress, Port, sendWrapper);
                     fileStream.Close();
                 }
                 catch (ArgumentException ex) { Log.Error("網路通訊異常請檢查", ex); ErrorStr = "網路通訊異常請檢查"; }
                 catch (ConnectionSetupException ex) { Log.Error("網路通訊異常請檢查", ex); ErrorStr = "網路通訊異常請檢查"; }
                 catch (ConnectionSendTimeoutException ex) { Log.Error("接收端程式異常", ex); ErrorStr = "接收端程式異常"; }
                 catch (Exception ex) { Log.Error(ex, "傳送檔案失敗"); }
             }
             break;
         }
     }
     catch (FileNotFoundException ex) { Log.Error("搜尋不到或未有檔案產生", ex); ErrorStr = "搜尋不到或未有檔案產生"; }
     catch (ObjectDisposedException ex) { Log.Error("檔案刪除後未有檔案產生", ex); ErrorStr = "檔案刪除後未有檔案產生"; }
     catch (DirectoryNotFoundException ex) { Log.Error("找不到檔案路徑", ex); ErrorStr = "找不到檔案路徑"; }
 }
        void OpenFileSend()
        {
            long totalBytesSent = 0;

            //Get the connection to the target
            Connection connection = TCPConnection.GetConnection(new ConnectionInfo(this.serverIp, this.serverPort));

            OpenFileDialog fd = new OpenFileDialog();

            if (fd.ShowDialog() == DialogResult.OK)
            {
                string filePath = fd.FileName;
                var    fileName = System.IO.Path.GetFileName(filePath);

                using (var file = new FileStream(filePath, FileMode.Open))
                {
                    using (var safeStream = new ThreadSafeStream(file))
                    {
                        var sendChunkSizeBytes = (long)(file.Length / 20.0) + 1;

                        //Limit send chunk size to 500MB
                        const long maxChunkSizeBytes = 500L * 1024L * 1024L;
                        if (sendChunkSizeBytes > maxChunkSizeBytes)
                        {
                            sendChunkSizeBytes = maxChunkSizeBytes;
                        }

                        totalBytesSent = 0;
                        do
                        {
                            //Check the number of bytes to send as the last one may be smaller
                            var bytesToSend = (totalBytesSent + sendChunkSizeBytes < file.Length ? sendChunkSizeBytes : file.Length - totalBytesSent);

                            //Wrap the threadSafeStream in a StreamSendWrapper so that we can get NetworkComms.Net
                            //to only send part of the stream.
                            using (var streamWrapper = new StreamSendWrapper(safeStream, totalBytesSent, bytesToSend))
                            {
                                //We want to record the packetSequenceNumber
                                long packetSequenceNumber;

                                connection.SendObject("PartitionedSend", streamWrapper);
                                //Send the select data
                                //connection.SendObject("PartialFileData", streamWrapper, NetworkComms.DefaultSendReceiveOptions, out packetSequenceNumber);
                                //Send the associated SendInfo for this send so that the remote can correctly rebuild the data
                                //connection.SendObject("PartialFileDataInfo", new SendInfo(fileName, file.Length, totalBytesSent, packetSequenceNumber));
                                totalBytesSent += bytesToSend;
                            }
                        } while (totalBytesSent < file.Length);
                    }
                }
            }
        }
Beispiel #5
0
        private void Constructor(string sendingPacketTypeStr, string requestReturnPacketTypeStr, object packetObject, SendReceiveOptions options)
        {
            if (sendingPacketTypeStr == null || sendingPacketTypeStr == "")
            {
                throw new ArgumentNullException("sendingPacketTypeStr", "The provided string can not be null or zero length.");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options", "The provided SendReceiveOptions cannot be null.");
            }

            if (packetObject == null)
            {
                this.packetData = new StreamSendWrapper(new ThreadSafeStream(new MemoryStream(new byte[0], 0, 0, false, true), true));
            }
            else
            {
                if (options.DataSerializer == null)
                {
                    throw new ArgumentNullException("options", "The provided SendReceiveOptions.DataSerializer cannot be null.");
                }
                this.packetData = options.DataSerializer.SerialiseDataObject(packetObject, options.DataProcessors, options.Options);
            }

            //We only calculate the checkSum if we are going to use it
            string hashStr = null;

            if (NetworkComms.EnablePacketCheckSumValidation)
            {
                hashStr = NetworkComms.MD5Bytes(packetData.ThreadSafeStream.ToArray(packetData.Start, packetData.Length));
            }

            this.packetHeader = new PacketHeader(sendingPacketTypeStr, packetData.Length, requestReturnPacketTypeStr,
                                                 options.Options.ContainsKey("ReceiveConfirmationRequired"),
                                                 hashStr,
                                                 options.Options.ContainsKey("IncludePacketConstructionTime"));

            //Add an identifier specifying the serializers and processors we have used
            this.packetHeader.SetOption(PacketHeaderLongItems.SerializerProcessors, DPSManager.CreateSerializerDataProcessorIdentifier(options.DataSerializer, options.DataProcessors));

            if (NetworkComms.LoggingEnabled)
            {
                NetworkComms.Logger.Trace(" ... creating comms packet. PacketObject data size is " + packetData.Length.ToString() + " bytes");
            }
        }