Пример #1
0
 /// <summary>
 /// Send file
 /// </summary>
 /// <param name="FileName">Path File</param>
 public bool SendFile(string FileName)
 {
     try
     {
         mainSocket.BeginSendFile(FileName, new AsyncCallback(FileSendCallback), mainSocket);
         return(true);
     }
     catch (FileNotFoundException se)
     {
         if (OnError != null)
         {
             OnError(se.Message, null, 0);
         }
         return(false);
     }
     catch (ObjectDisposedException se)
     {
         if (OnError != null)
         {
             OnError(se.Message, null, 0);
         }
         return(false);
     }
     catch (SocketException se)
     {
         if (OnError != null)
         {
             OnError(se.Message, mainSocket, se.ErrorCode);
         }
         return(false);
     }
 }
Пример #2
0
 public void IndividualBeginEndMethods_Disposed_ThrowsObjectDisposedException()
 {
     using Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     s.Dispose();
     Assert.Throws <ObjectDisposedException>(() => s.BeginSendFile(null, null, null));
     Assert.Throws <ObjectDisposedException>(() => s.BeginSendFile(null, null, null, TransmitFileOptions.UseDefaultWorkerThread, null, null));
 }
Пример #3
0
 public void NotConnected_ThrowsException()
 {
     using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
     {
         Assert.Throws <NotSupportedException>(() => s.SendFile(null));
         Assert.Throws <NotSupportedException>(() => s.BeginSendFile(null, null, null));
         Assert.Throws <NotSupportedException>(() => s.BeginSendFile(null, null, null, TransmitFileOptions.UseDefaultWorkerThread, null, null));
     }
 }
Пример #4
0
 public void Disposed_ThrowsException()
 {
     using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
     {
         s.Dispose();
         Assert.Throws <ObjectDisposedException>(() => s.SendFile(null));
         Assert.Throws <ObjectDisposedException>(() => s.SendFile(null, null, null, TransmitFileOptions.UseDefaultWorkerThread));
         Assert.Throws <ObjectDisposedException>(() => s.SendFile(null, ReadOnlySpan <byte> .Empty, ReadOnlySpan <byte> .Empty, TransmitFileOptions.UseDefaultWorkerThread));
         Assert.Throws <ObjectDisposedException>(() => s.BeginSendFile(null, null, null));
         Assert.Throws <ObjectDisposedException>(() => s.BeginSendFile(null, null, null, TransmitFileOptions.UseDefaultWorkerThread, null, null));
         Assert.Throws <ObjectDisposedException>(() => s.EndSendFile(null));
     }
 }
Пример #5
0
        /*
         * This function sends the file with the given filename to the client
         * on the end of the socketObj by first sending the filesize, then transfering
         * the data.
         */
        private void dataTransferToClient(Object socketObj, string username, string filename)
        {
            Socket socket        = (Socket)socketObj;
            string directoryPath = serverPath.Text + "\\" + username;
            string filePath      = directoryPath + "\\" + filename;

            printLogger("Server is sending the file " + filename + " for user: "******"Exception occured during data transfer: " + exc.Message);
                return;
            }
        }
Пример #6
0
        /// <summary>
        /// Sends the file <paramref name="fileName"/> to a connected <see cref="Socket"/> object.
        /// </summary>
        /// <param name="socket">The target socket.</param>
        /// <param name="fileName">A string that contains the path and name of the file to send. This parameter can be <see langword="null"/>.</param>
        /// <param name="preBuffer">A byte array that contains data to be sent before the file is sent. This parameter can be <see langword="null"/>.</param>
        /// <param name="postBuffer">A byte array that contains data to be sent after the file is sent. This parameter can be <see langword="null"/>.</param>
        /// <param name="flags">A bitwise combination of <see cref="TransmitFileOptions"/> values.</param>
        /// <exception cref="FileNotFoundException">The file <paramref name="fileName"/> was not found.</exception>
        /// <exception cref="SocketException">An error occurred when attempting to access the <paramref name="socket"/>.</exception>
        /// <exception cref="NotSupportedException">The operating system is not Windows NT or later or rhe <paramref name="socket"/> is not connected to a remote host.</exception>
        /// <exception cref="ObjectDisposedException">Thrown if the <paramref name="socket"/> has been closed.</exception>
        /// <returns>Returns <see cref="IAsyncOperation"/> representing the asynchronous operation.</returns>
        public static IAsyncOperation SendFileAsync(this Socket socket, string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
        {
            var op = new ApmResult <Socket, VoidResult>(socket);

            socket.BeginSendFile(fileName, preBuffer, postBuffer, flags, OnSendFileCompleted, op);
            return(op);
        }
Пример #7
0
        // <snippet9>
        public static void AsynchronousFileSend()
        {
            // Send a file to a remote device.

            // Establish the remote endpoint for the socket.
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress   ipAddress  = ipHostInfo.AddressList[0];
            IPEndPoint  remoteEP   = new IPEndPoint(ipAddress, 11000);

            // Create a TCP/IP socket.
            Socket client = new Socket(AddressFamily.InterNetwork,
                                       SocketType.Stream, ProtocolType.Tcp);

            // Connect to the remote endpoint.
            client.BeginConnect(remoteEP,
                                new AsyncCallback(ConnectCallback), client);

            // Wait for connect.
            connectDone.WaitOne();

            // There is a text file test.txt in the root directory.
            string fileName = "C:\\test.txt";

            // Send file fileName to the remote device.
            Console.WriteLine(fileName);
            client.BeginSendFile(fileName, new AsyncCallback(FileSendCallback), client);

            // Release the socket.
            client.Shutdown(SocketShutdown.Both);
            client.Close();
        }
Пример #8
0
        //public static Task<ArraySegment<byte>> BeginReceiveArraySegmentFromAsync(this Socket socket, ArraySegment<byte> segment, ref EndPoint remoteEnd)
        //{
        //    return socket.ReceiveFromAsync(segment, ref remoteEnd).ContinueWith((n) => segment.Take(n.Result));
        //}

        #endregion

        public static Task SendFile(this Socket socket, string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions options)
        {
            return(Task.Factory.FromAsync(
                       socket.BeginSendFile(fileName, preBuffer, postBuffer, options, null, null),
                       socket.EndSendFile
                       ));
        }
Пример #9
0
        /// <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">The target socket.</param>
        /// <param name="fileName">A string that contains the path and name of the file to send. This parameter can be <see langword="null"/>.</param>
        /// <exception cref="FileNotFoundException">The file <paramref name="fileName"/> was not found.</exception>
        /// <exception cref="SocketException">An error occurred when attempting to access the <paramref name="socket"/>.</exception>
        /// <exception cref="NotSupportedException">The operating system is not Windows NT or later or rhe <paramref name="socket"/> is not connected to a remote host.</exception>
        /// <exception cref="ObjectDisposedException">Thrown if the <paramref name="socket"/> has been closed.</exception>
        /// <returns>Returns <see cref="IAsyncOperation"/> representing the asynchronous operation.</returns>
        public static IAsyncOperation SendFileAsync(this Socket socket, string fileName)
        {
            var op = new ApmResult <Socket, VoidResult>(socket);

            socket.BeginSendFile(fileName, OnSendFileCompleted, op);
            return(op);
        }
Пример #10
0
        protected override void SendFile(string FileName, byte[] header, byte[] footer, bool Async, CompressionType Compression)
        {
            try
            {
                fileSendSize = (uint)header.Length + (uint)footer.Length + (ulong)(new System.IO.FileInfo(FileName).Length);

                if (Async)
                {
                    sock.BeginSendFile(FileName, header, footer, TransmitFileOptions.UseSystemThread, EndSendFile, sock);
                }
                else
                {
                    sock.SendFile(FileName, header, footer, TransmitFileOptions.UseDefaultWorkerThread);
                    bytesSent = bytesSent + fileSendSize;
                    //Console.WriteLine("Sent File: [{0}] Total:[{1}]", fileSent, _bytesSent);
                    if (Compression != CompressionType.NoCompression)
                    {
                        try { System.IO.File.Delete(FileName); }
                        catch { }
                    }
                }
            }
            catch (Exception ex)
            {
                if (stopped)
                {
                    // We forcefully closed this socket therefore this exception was expected and we can ignore it
                }
                else
                {
                    Disconnect(ex);
                }
            }
        }
Пример #11
0
 public static Task SendFile(this Socket socket, string fileName)
 {
     return(Task.Factory.FromAsync(
                socket.BeginSendFile(fileName, null, null),
                socket.EndSendFile
                ));
 }
Пример #12
0
 public async Task SendFile(string fileName)
 {
     var lengthByte = CreateFirstMessage(new FileInfo(fileName).Length);
     await Task.Factory.FromAsync(
         socket.BeginSendFile(fileName, lengthByte, null, TransmitFileOptions.UseKernelApc, null, null),
         socket.EndSendFile);
 }
Пример #13
0
        public void SendFile_APM(IPAddress listenAt, bool sendPreAndPostBuffers, int bytesToSend)
        {
            const int ListenBacklog = 1, TestTimeout = 30000;

            // Create file to send
            byte[]     preBuffer, postBuffer;
            Fletcher32 sentChecksum;
            string     filename = CreateFileToSend(bytesToSend, sendPreAndPostBuffers, out preBuffer, out postBuffer, out sentChecksum);

            // Start server
            using (var listener = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
            {
                listener.BindToAnonymousPort(listenAt);
                listener.Listen(ListenBacklog);

                int bytesReceived    = 0;
                var receivedChecksum = new Fletcher32();

                Task serverTask = Task.Run(async() =>
                {
                    using (var serverStream = new NetworkStream(await listener.AcceptAsync(), ownsSocket: true))
                    {
                        var buffer = new byte[256];
                        int bytesRead;
                        while ((bytesRead = await serverStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
                        {
                            bytesReceived += bytesRead;
                            receivedChecksum.Add(buffer, 0, bytesRead);
                        }
                    }
                });
                Task clientTask = Task.Run(async() =>
                {
                    using (var client = new Socket(listener.LocalEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
                    {
                        await client.ConnectAsync(listener.LocalEndPoint);
                        await Task.Factory.FromAsync(
                            (callback, state) => client.BeginSendFile(filename, preBuffer, postBuffer, TransmitFileOptions.UseDefaultWorkerThread, callback, state),
                            iar => client.EndSendFile(iar),
                            null);
                        client.Shutdown(SocketShutdown.Send);
                    }
                });

                // Wait for the tasks to complete
                Task <Task> firstCompleted = Task.WhenAny(serverTask, clientTask);
                Assert.True(firstCompleted.Wait(TestTimeout), "Neither client nor server task completed within allowed time");
                firstCompleted.Result.GetAwaiter().GetResult();
                Assert.True(Task.WaitAll(new[] { serverTask, clientTask }, TestTimeout), $"Tasks didn't complete within allowed time. Server:{serverTask.Status} Client:{clientTask.Status}");

                // Validate the results
                Assert.Equal(bytesToSend, bytesReceived);
                Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum);
            }

            // Clean up the file we created
            File.Delete(filename);
        }
Пример #14
0
        /// <summary>
        /// Extends BeginSendFile so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// socket.BeginSendFile(fileName, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginSendFile(this Socket socket, String fileName, AsyncCallback callback)
        {
            if (socket == null)
            {
                throw new ArgumentNullException("socket");
            }

            return(socket.BeginSendFile(fileName, callback, null));
        }
Пример #15
0
        /// <summary>
        /// Extends BeginSendFile so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// socket.BeginSendFile(fileName, preBuffer, postBuffer, flags, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginSendFile(this Socket socket, String fileName, Byte[] preBuffer, Byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback)
        {
            if (socket == null)
            {
                throw new ArgumentNullException("socket");
            }

            return(socket.BeginSendFile(fileName, preBuffer, postBuffer, flags, callback, null));
        }
Пример #16
0
        public void SendFile(string filePath)
        {
            if (IsConnected() == false)
            {
                return;
            }

            socket.BeginSendFile(filePath, new AsyncCallback(OnFileSended), socket);
        }
Пример #17
0
        public static void SendFileAPM(this Socket socket, string filename, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, Action handler)
        {
            var callback = new AsyncCallback(asyncResult =>
            {
                ((Socket)asyncResult.AsyncState).EndSendFile(asyncResult);
                handler();
            });

            socket.BeginSendFile(filename, preBuffer, postBuffer, flags, callback, socket);
        }
Пример #18
0
        public Task SendFile(string path, byte[] preBuffer, byte[] postBuffer, CancellationToken cancellationToken)
        {
            var options = TransmitFileOptions.UseDefaultWorkerThread;

            var completionSource = new TaskCompletionSource <bool>();

            var result = Socket.BeginSendFile(path, preBuffer, postBuffer, options, new AsyncCallback(FileSendCallback), new Tuple <Socket, string, TaskCompletionSource <bool> >(Socket, path, completionSource));

            return(completionSource.Task);
        }
Пример #19
0
 private void SendFile(String path, Socket target)
 {
     try
     {
         target.BeginSendFile(path, new AsyncCallback(SendFileCall), target);
     }
     catch (IOException e)
     {
         Console.WriteLine(e.Message);
         SendText("Unable to access file", target);
     }
 }
 /// <inheritdoc/>
 protected override void BeginSendFile(IWriteRequest request, IFileRegion file)
 {
     try
     {
         Socket.BeginSendFile(file.FullName, SendFileCallback, new SendingContext(Socket, file));
     }
     catch (ObjectDisposedException)
     {
         // ignore
     }
     catch (Exception ex)
     {
         EndSend(ex);
     }
 }
Пример #21
0
        public static void SendFileAPM(this Socket socket, string filename, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, Action <Exception> handler)
        {
            var callback = new AsyncCallback(asyncResult =>
            {
                Exception exc = null;
                try
                {
                    ((Socket)asyncResult.AsyncState).EndSendFile(asyncResult);
                }
                catch (Exception e) { exc = e; }
                handler(exc);
            });

            socket.BeginSendFile(filename, preBuffer, postBuffer, flags, callback, socket);
        }
Пример #22
0
        private Task TransmitFileOverSocket(string path, long offset, long count, FileShareMode fileShareMode, CancellationToken cancellationToken)
        {
            var ms = GetHeaders(false);

            byte[] preBuffer;
            if (ms != null)
            {
                using (var msCopy = new MemoryStream())
                {
                    ms.CopyTo(msCopy);
                    preBuffer = msCopy.ToArray();
                }
            }
            else
            {
                return(TransmitFileManaged(path, offset, count, fileShareMode, cancellationToken));
            }

            _stream.Flush();

            _logger.Info("Socket sending file {0}", path);

            var taskCompletion = new TaskCompletionSource <bool>();

            Action <IAsyncResult> callback = callbackResult =>
            {
                try
                {
                    _socket.EndSendFile(callbackResult);
                    taskCompletion.TrySetResult(true);
                }
                catch (Exception ex)
                {
                    taskCompletion.TrySetException(ex);
                }
            };

            var result = _socket.BeginSendFile(path, preBuffer, _emptyBuffer, TransmitFileOptions.UseDefaultWorkerThread, new AsyncCallback(callback), null);

            if (result.CompletedSynchronously)
            {
                callback(result);
            }

            cancellationToken.Register(() => taskCompletion.TrySetCanceled());

            return(taskCompletion.Task);
        }
    private static void SendFile(Socket client, String fileName)
    {
        // Convert the string data to byte data using ASCII encoding.
        //byte[] byteData = Encoding.ASCII.GetBytes(data);


        if (File.Exists(fileName))
        {
            // Begin sending the data to the remote device.
            client.BeginSendFile(fileName, new AsyncCallback(SendCallback), client);
        }
        else
        {
            Console.WriteLine("File is not exist : " + fileName);
        }
    }
 /// <summary>
 /// Send file by connecting selected
 /// </summary>
 /// <param name="FileName">Path File</param>
 /// <param name="PreString">Message sent before the file</param>
 /// <param name="PosString">Message sent after the File</param>
 /// <param name="SocketIndex">Index of connection</param>
 public bool SendFile(string FileName, string PreString, string PosString, int SocketIndex)
 {
     if ((Clients.Count - 1) >= SocketIndex)
     {
         Socket workerSocket = (Socket)Clients[SocketIndex];
         try
         {
             byte[] preBuf  = Encoding.UTF8.GetBytes(PreString);
             byte[] postBuf = Encoding.UTF8.GetBytes(PosString);
             workerSocket.BeginSendFile(FileName, preBuf, postBuf, 0, new AsyncCallback(FileSendCallback), workerSocket);
             return(true);
         }
         catch (ArgumentException se)
         {
             if (OnError != null)
             {
                 OnError(se.Message, null, 0);
             }
             return(false);
         }
         catch (ObjectDisposedException se)
         {
             if (OnError != null)
             {
                 OnError(se.Message, null, 0);
             }
             return(false);
         }
         catch (SocketException se)
         {
             if (OnError != null)
             {
                 OnError(se.Message, workerSocket, se.ErrorCode);
             }
             return(false);
         }
     }
     else
     {
         if (OnError != null)
         {
             OnError("Index was out of range. Must be non-negative and less than the size of the collection.", null, 0);
         }
         return(false);
     }
 }
 /// <summary>
 /// Send file by connecting selected
 /// </summary>
 /// <param name="FileName">Path File</param>
 /// <param name="SocketIndex">Index of connection</param>
 public bool SendFile(string FileName, int SocketIndex)
 {
     if ((Clients.Count - 1) >= SocketIndex)
     {
         Socket workerSocket = (Socket)Clients[SocketIndex];
         try
         {
             workerSocket.BeginSendFile(FileName, new AsyncCallback(FileSendCallback), workerSocket);
             return(true);
         }
         catch (FileNotFoundException se)
         {
             if (OnError != null)
             {
                 OnError(se.Message, null, 0);
             }
             return(false);
         }
         catch (ObjectDisposedException se)
         {
             if (OnError != null)
             {
                 OnError(se.Message, null, 0);
             }
             return(false);
         }
         catch (SocketException se)
         {
             if (OnError != null)
             {
                 OnError(se.Message, workerSocket, se.ErrorCode);
             }
             return(false);
         }
     }
     else
     {
         if (OnError != null)
         {
             OnError("Index was out of range. Must be non-negative and less than the size of the collection.", null, 0);
         }
         return(false);
     }
 }
Пример #26
0
        // </snippet9>


        // <snippet10>
        public static void AsynchronousFileSendWithBuffers()
        {
            // Send a file asynchronously to the remote device. Send a buffer before the file and a buffer afterwards.

            // Establish the remote endpoint for the socket.
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress   ipAddress  = ipHostInfo.AddressList[0];
            IPEndPoint  remoteEP   = new IPEndPoint(ipAddress, 11000);

            // Create a TCP/IP socket.
            Socket client = new Socket(AddressFamily.InterNetwork,
                                       SocketType.Stream, ProtocolType.Tcp);

            // Connect to the remote endpoint.
            client.BeginConnect(remoteEP,
                                new AsyncCallback(ConnectCallback), client);

            // Wait for connect.
            connectDone.WaitOne();

            // Send a file fileName to the remote device with preBuffer and postBuffer data.
            // Create the preBuffer data.
            string string1 = String.Format("This is text data that precedes the file.{0}", Environment.NewLine);

            byte[] preBuf = Encoding.ASCII.GetBytes(string1);

            // Create the postBuffer data.
            string string2 = String.Format("This is text data that will follow the file.{0}", Environment.NewLine);

            byte[] postBuf = Encoding.ASCII.GetBytes(string2);

            // There is a file test.txt in the root directory.
            string fileName = "C:\\test.txt";

            //Send file fileName with buffers and default flags to the remote device.
            Console.WriteLine(fileName);
            client.BeginSendFile(fileName, preBuf, postBuf, 0, new AsyncCallback(AsynchronousFileSendCallback), client);

            // Release the socket.
            client.Shutdown(SocketShutdown.Both);
            client.Close();
        }
Пример #27
0
        private void clientSend_Click(object sender, EventArgs e)
        {
            string       operationCode = "UPL";
            UTF8Encoding aEncoder      = new UTF8Encoding();

            byte[] codeInBytes = aEncoder.GetBytes(operationCode);
            cliSocket.Send(codeInBytes);

            printLogger("System is uploading the file/folder... ");
            long   filesize = new FileInfo(clientText.Text).Length;
            string filename = Path.GetFileName(clientText.Text);

            byte[] filenameInBytes = aEncoder.GetBytes(filename);
            byte[] fileInfo        = new byte[12 + filename.Length];

            //Filling fileInfo byte array
            Buffer.BlockCopy(BitConverter.GetBytes(filenameInBytes.Length), 0, fileInfo, 0, 4);
            Buffer.BlockCopy(filenameInBytes, 0, fileInfo, 4, filenameInBytes.Length);
            Buffer.BlockCopy(BitConverter.GetBytes(filesize), 0, fileInfo, 4 + filenameInBytes.Length, sizeof(long));

            try
            {
                cliSocket.Send(fileInfo);
            }
            catch (Exception exc)
            {
                MessageBox.Show("Exception occured during data transfer: " + exc.Message);
                return;
            }

            Thread.Sleep(1000);

            try
            {
                cliSocket.BeginSendFile(clientText.Text, new AsyncCallback(FileSendCallback), cliSocket);
            }
            catch (Exception exc)
            {
                MessageBox.Show("Exception occured during data transfer: " + exc.Message);
                return;
            }
        }
Пример #28
0
        private void ReadCallback(IAsyncResult ar)
        {
            try
            {
                Socket handler  = (Socket)ar.AsyncState;
                int    received = handler.EndReceive(ar);

                if (received > 0)
                {
                    sb.Append(Encoding.ASCII.GetString(buffer, 0, received));
                    string content = sb.ToString();

                    buffer = new byte[ServerConstants.BufferSize];

                    if (content.IndexOf(ServerConstants.EOF) > -1)
                    {
                        content = content.Substring(0, content.Length - 5);

                        var deserialized = JsonConvert.DeserializeObject <PackageWrapper>(content);
                        if (deserialized.PackageType == typeof(FileSearch))
                        {
                            FileSearch fs = (FileSearch)JsonConvert.DeserializeObject(Convert.ToString(deserialized.Package), deserialized.PackageType);
                            handler.BeginSendFile(upPath + fs.FileName, new AsyncCallback(SendCallback), handler);
                        }
                    }

                    else
                    {
                        handler.BeginReceive(buffer, 0, ServerConstants.BufferSize, 0, new AsyncCallback(ReadCallback), handler);
                    }
                }

                sb.Clear();
                buffer = new byte[ServerConstants.BufferSize];
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Пример #29
0
        public async Task SendFile_NoFile_Succeeds(bool useAsync, bool usePreBuffer, bool usePostBuffer)
        {
            using var client   = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            using var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listener.BindToAnonymousPort(IPAddress.Loopback);
            listener.Listen(1);

            client.Connect(listener.LocalEndPoint);
            using Socket server = listener.Accept();

            if (useAsync)
            {
                await Task.Factory.FromAsync <string>(server.BeginSendFile, server.EndSendFile, null, null);
            }
            else
            {
                server.SendFile(null);
            }
            Assert.Equal(0, client.Available);

            byte[] preBuffer     = usePreBuffer ? new byte[1] : null;
            byte[] postBuffer    = usePostBuffer ? new byte[1] : null;
            int    bytesExpected = (usePreBuffer ? 1 : 0) + (usePostBuffer ? 1 : 0);

            if (useAsync)
            {
                await Task.Factory.FromAsync((c, s) => server.BeginSendFile(null, preBuffer, postBuffer, TransmitFileOptions.UseDefaultWorkerThread, c, s), server.EndSendFile, null);
            }
            else
            {
                server.SendFile(null, preBuffer, postBuffer, TransmitFileOptions.UseDefaultWorkerThread);
            }

            byte[] receiveBuffer = new byte[1];
            for (int i = 0; i < bytesExpected; i++)
            {
                Assert.Equal(1, client.Receive(receiveBuffer));
            }

            Assert.Equal(0, client.Available);
        }
Пример #30
0
        public static void IniciarServidor()
        {
            try
            {
                //Colocar ip da rede
                System.Net.IPAddress localadrr = System.Net.IPAddress.Parse("192.168.1.5");

                TcpListener escutar = new TcpListener(localadrr, 12345);

                escutar.Start();

                Socket soc = escutar.AcceptSocket();

                if (soc.Connected)
                {
                    mensagemServidor += " \n Conectado com o cliente.";
                    // Para mandar JSON
                    string Filename = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory.ToString()) + "UVA.JSON";

                    //  Tentativa de enviar um arquivo
                    //string Filename = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory.ToString()) + "ProMEDCT0051.obj";


                    //soc.BeginSendFile(Filename, new AsyncCallback(FileSendCallback), soc);
                    soc.BeginSendFile(Filename, delegate(IAsyncResult ar) {
                        Socket client = (Socket)ar.AsyncState;
                        // Complete sending the data to the remote device.
                        client.EndSendFile(ar);

                        escutar.Stop();
                    }, soc);
                }
            } catch (Exception ex)
            {
                mensagemServidor += "Não foi possivel estabelecer conexão." + "\n" + ex.Message;
            }
        }
    private static void SendFile(Socket client, String fileName)
    {
        // Convert the string data to byte data using ASCII encoding.
        //byte[] byteData = Encoding.ASCII.GetBytes(data);


        if (File.Exists(fileName))
        {
            // Begin sending the data to the remote device.
            client.BeginSendFile(fileName, new AsyncCallback(SendCallback), client);
        }
        else
        {
            Console.WriteLine("File is not exist : " + fileName);
        }
    }