0

Im working on a project and Im stuck on the file transfering ... so far its working but in my mind it's not the right way. When I send the file I wait 1 second after it was send. After that I send the stop command to the receiver so that he (the receiver) can close the file . Every byte array send is made to string so that I can check if the received byte array is the stop command. Without the sleep command , the stop command wont be send separated (it will be send with another byte array). Is there any way to stop the file transfering more efficient without closing the sockets ? Sending function:

public void sendFile()
    {
        string filename = Path.GetFileName(fileLocation);
        byte[] SendingBuffer = null;
        server = client.GetStream();
        int BufferSize = 1024;
        try
        {
            using (FileStream fs = File.Open(fileLocation, FileMode.Open, FileAccess.Read, FileShare.None))
            {
                int NoOfPackets = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(fs.Length) / Convert.ToDouble(BufferSize)));
                int TotalLenght = (int)fs.Length, CurrentPacketLengh = 0;
                mainWindowClass.progressBar2.Dispatcher.Invoke(new Action(()=> mainWindowClass.progressBar2.Maximum = NoOfPackets));
                sendCommand("sndfil"+ filename, "c0mm@nds t0 s3nd %!3");
                for (int i = 0; i < NoOfPackets; i++)
                {
                    //MessageBox.Show(NoOfPackets.ToString() + " " + i);
                    if (TotalLenght > BufferSize)
                    {
                        CurrentPacketLengh = BufferSize;
                        TotalLenght = TotalLenght - CurrentPacketLengh;
                    }
                    else
                        CurrentPacketLengh = TotalLenght;
                    SendingBuffer = new byte[CurrentPacketLengh];
                    fs.Read(SendingBuffer, 0, CurrentPacketLengh);
                    server.Write(SendingBuffer, 0, (int)SendingBuffer.Length);
                    mainWindowClass.progressBar2.Dispatcher.Invoke(new Action(() => mainWindowClass.progressBar2.Value++));
                }
                Thread.Sleep(1000);
                byte[] outStream = System.Text.Encoding.ASCII.GetBytes("stopfile");
                server.Write(outStream, 0, (int)outStream.Length);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        mainWindowClass.progressBar2.Dispatcher.Invoke(new Action(() => mainWindowClass.progressBar2.Value=0));
    }

Receiving function:

 public void receiveFile(string name)
    {
        string fileName = (System.IO.Path.Combine(mainWindowClass.saveFolder, name));
        byte[] RecData = new byte[1024];
        int RecBytes;
        NetworkStream netstream = null;
        try
        {
            int total = 0;
            netstream = client.GetStream();
            FileStream Fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
            RecBytes = netstream.Read(RecData, 0, RecData.Length);
            char[] chars = new char[RecBytes];
            System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
            int charLen = d.GetChars(RecData, 0, RecBytes, chars, 0);
            System.String recv = new System.String(chars);
            while (recv!="stopfile")
            {
                total += RecData.Length;
                Fs.Write(RecData, 0, RecBytes);
                RecBytes = netstream.Read(RecData, 0, RecData.Length);
                chars = new char[RecBytes];
                d = System.Text.Encoding.UTF8.GetDecoder();
                charLen = d.GetChars(RecData, 0, RecBytes, chars, 0);
                recv = new System.String(chars);
            }
            Fs.Close();
            mainWindowClass.testLabel.Dispatcher.Invoke(new Action(() => mainWindowClass.testLabel.Content += total.ToString()));
        }
        catch (Exception e)
        {
            MessageBox.Show(e.ToString());
        }
    }

I've searched on google the solution , but all I found was to close the client/server.

Alecs
  • 1
  • First send file's size, then file itself. Then you know exactly when transfer is done. See here for example of proper messaging via sockets - http://stackoverflow.com/a/37148335/5311735 – Evk May 14 '16 at 16:02
  • I will try it now ... comming back to tell you if it works or not – Alecs May 14 '16 at 16:05
  • Instead of using TCP and implementing a protocol on it, I would use HttpListener + WebClient (or HttpClient)...... – Eser May 14 '16 at 16:07
  • 1
    Don't invent your own protocol, use existing protocols. If you really want to reinvent the wheel, you could use something like a message length prefix. – CodeCaster May 14 '16 at 16:17
  • @Eser : Http is much slower than just TCP. – Visual Vincent May 14 '16 at 16:36
  • @VisualVincent Other than overhead of some headers, why should it be slower? it also works on TCP (BTW: a few hundred bytes are nothing when considering you are downloading a file.)... – Eser May 14 '16 at 16:43
  • It worked with Evk method (thank you). I dont want to use another way because wednesday its my deadline and I dont want to modify my entire project. After that I will study more ways to send data or files... thank you for help – Alecs May 14 '16 at 16:48
  • @Eser : I know HTTP uses TCP, and so does FTP. Yet FTP is faster than HTTP. From my experience HTTP slower compared to raw TCP or TCP with a small packet handling layer. Also a few hundred bytes matters to me (don't know about the OP though) :). – Visual Vincent May 14 '16 at 16:54
  • @Alecs : There's no need to change your entire project either. TCP with a packet handling layer is still better IMO ;). – Visual Vincent May 14 '16 at 16:55
  • @VisualVincent OK, I got it, We should believe it because you think so... – Eser May 14 '16 at 17:06
  • @Eser : No... But HTTP is usually a bit slower. Here's a Stack Overflow post about it, with a pretty interesting link in the answer: http://stackoverflow.com/a/1217954/3740093 – Visual Vincent May 14 '16 at 17:13
  • 2
    @VisualVincent As I said before, other than overhead of headers, there is no reason for HTTP to be slower. Maybe you are confused with general purpose http servers that does a lot of thing for checking the request and preparing an answer. And again, I mentioned the use of HttpListener class, whose overhead wouldn't be much compared to a TCP listener and it is preferable most of the times because it eliminates the need to create a custom protocol and handles a lot of thing for you. To be able to use standard clients like downloader-helpers is another advantage. – Eser May 14 '16 at 17:26
  • @VisualVincent As an exercise, create a Tcp listener that reads a few lines of strings from clients and writes a few lines of text and then the actual data. Here is your Http server. – Eser May 14 '16 at 17:40
  • @Eser : I've just tried using the HttpListener for a performance test but I don't really understand how it works and how I'll send data through it... But what I do know however is my way around regular TCP, and I've already done more than sending strings through it so I'll pass the "exercise" of yours :). [Infact I have an answer similar to Evk's.](http://stackoverflow.com/a/35240061/3740093) – Visual Vincent May 14 '16 at 17:58
  • @Eser : I might confuse .NET HTTP communication with HTTP web servers' slowness as you say, and I'm not much into the HTTP business... Though I still find that previous link rather interesting. – Visual Vincent May 14 '16 at 17:59
  • 1
    @VisualVincent _"HTTP is slow, use TCP"_ was said before the birth of many issue-causing home-grown protocols that don't actually perform that well in terms of both performance and maintainability. You _really_ need to consider whether you want to write yet another custom protocol that shaves off those handful of bytes from a common protocol that actually don't matter that much. – CodeCaster May 15 '16 at 11:29
  • @CodeCaster : Well I guess it all depends on what the creator wants. I wrote a custom protocol for my application which only adds 5 extra bytes per send - though to me small size is critical :). And it actually performs pretty well. – Visual Vincent May 15 '16 at 11:33

0 Answers0