/// <summary>
        /// Sends a file and buffers of data asynchronously to a connected <see cref="Socket" />.
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="filename"></param>
        /// <param name="preBuffer"></param>
        /// <param name="postBuffer"></param>
        /// <param name="flags"></param>
        /// <returns></returns>
        public static Task SendFileAsync(this Socket socket, string filename, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
        {
            NotNull(socket, nameof(socket));

            var tcs = new TaskCompletionSource <bool>(socket);

            socket.BeginSendFile(filename, preBuffer, postBuffer, flags, BeginSendFileCallback, tcs);
            return(tcs.Task);
        }
        /// <summary>
        /// Sends the file <paramref name="filename" /> to a connected <see cref="Socket" /> object using
        /// the <see cref="TransmitFileOptions.UseDefaultWorkerThread" /> flag.
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static Task SendFileAsync(this Socket socket, string filename)
        {
            NotNull(socket, nameof(socket));

            var tcs = new TaskCompletionSource <bool>(socket);

            socket.BeginSendFile(filename, BeginSendFileCallback, tcs);
            return(tcs.Task);
        }
Exemple #3
0
 public void SendFile(string file)
 {
     try
     {
         _socket.BeginSendFile(file, null, null);
     }
     catch (Exception e)
     {
         throw new Exception("Something went wrong sending file to the socket.\n" + e.Message);
     }
 }
        public static IObservable <Unit> SendFileObservable(this Socket socket, string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
        {
            Contract.Requires(socket != null);
            Contract.Ensures(Contract.Result <IObservable <Unit> >() != null);

            return(Task.Factory.FromAsync <string, Tuple <byte[], byte[]>, TransmitFileOptions>(
                       (fn, buffers, fg, callback, state) => socket.BeginSendFile(fn, buffers.Item1, buffers.Item2, fg, callback, state),
                       socket.EndSendFile,
                       fileName,
                       Tuple.Create(preBuffer, postBuffer),
                       flags,
                       state: null)
                   .ToObservable());
        }
Exemple #5
0
		public void SendAsyncFile ()
		{
			Socket serverSocket = StartSocketServer ();
			
			Socket clientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			clientSocket.Connect (serverSocket.LocalEndPoint);
			clientSocket.NoDelay = true;
						
			// Initialize buffer used to create testing file
			var buffer = new byte [1024];
			for (int i = 0; i < 1024; ++i)
				buffer [i] = (byte) (i % 256);
			
			string temp = Path.GetTempFileName ();
			try {
				// Testing file creation
				using (StreamWriter sw = new StreamWriter (temp)) {
					sw.Write (buffer);
				}

				var m = new ManualResetEvent (false);

				// Async Send File to server
				clientSocket.BeginSendFile(temp, (ar) => {
					Socket client = (Socket) ar.AsyncState;
					client.EndSendFile (ar);
					m.Set ();
				}, clientSocket);

				if (!m.WaitOne (1500))
					throw new TimeoutException ();
				m.Reset ();
			} finally {
				if (File.Exists (temp))
					File.Delete (temp);
					
				clientSocket.Close ();
				serverSocket.Close ();
			}
		}
Exemple #6
0
 System.IAsyncResult Utils.Wrappers.Interfaces.ISocket.BeginSendFile(string fileName, System.AsyncCallback callback, object state)
 {
     return(InternalSocket.BeginSendFile(fileName, callback, state));
 }
Exemple #7
0
		public void SendAsyncFile ()
		{
			Socket serverSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

			serverSocket.Bind (new IPEndPoint (IPAddress.Loopback, 0));
			serverSocket.Listen (1);

			var mReceived = new ManualResetEvent (false);

			serverSocket.BeginAccept (AsyncCall => {
				byte[] bytes = new byte [1024];

				Socket listener = (Socket)AsyncCall.AsyncState;
				Socket client = listener.EndAccept (AsyncCall);
				client.Receive (bytes, bytes.Length, 0);
				client.Close ();
				mReceived.Set ();
			}, serverSocket);
			
			Socket clientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			clientSocket.Connect (serverSocket.LocalEndPoint);
			clientSocket.NoDelay = true;
						
			// Initialize buffer used to create testing file
			var buffer = new byte [1024];
			for (int i = 0; i < 1024; ++i)
				buffer [i] = (byte) (i % 256);
			
			string temp = Path.GetTempFileName ();
			try {
				// Testing file creation
				using (StreamWriter sw = new StreamWriter (temp)) {
					sw.Write (buffer);
				}

				var mSent = new ManualResetEvent (false);

				// Async Send File to server
				clientSocket.BeginSendFile(temp, (ar) => {
					Socket client = (Socket) ar.AsyncState;
					client.EndSendFile (ar);
					mSent.Set ();
				}, clientSocket);

				if (!mSent.WaitOne (1500))
					throw new TimeoutException ();
				if (!mReceived.WaitOne (1500))
					throw new TimeoutException ();
			} finally {
				if (File.Exists (temp))
					File.Delete (temp);
					
				clientSocket.Close ();
				serverSocket.Close ();
			}
		}
Exemple #8
0
        /// <summary>
        /// Attempts to asynchronously serve a file on the specified socket.
        /// Sends a HTTP 404 error on the socket if the file is not found.
        /// </summary>
        /// <param name="filePath">The local path of a file</param>
        /// <param name="handler">The socket to send the file data on</param>
        private static void SendFile(string filePath, Socket handler)
        {
            if (File.Exists(filePath))
            {
                byte[] data = File.ReadAllBytes(filePath);

                // 200 OK
                string header = BuildResponseHeader(GetMimeType(filePath), data.Length, HttpStatusCode.OK);
                Send(handler, header);

                StateObject state = new StateObject();
                state.Socket = handler;
                state.Data.Append(filePath);
                handler.BeginSendFile(filePath, new AsyncCallback(SendFileCallback), state);
            }
            else
            {
                // 404 NotFound
                string code = (int)HttpStatusCode.NotFound + " " + HttpStatusCode.NotFound;
                Send(handler, BuildResponseHeader("text/plain; charset=UTF-8", code.Length, HttpStatusCode.NotFound));
                Send(handler, code);
            }
        }