Search code examples
c#socketsserverbuffersslstream

sending big file with socket to server c#


I'm trying to send a file about 250 kb to server but i have a corruption and it seemd that tottaly transfered some bytes only. The flow of command is Write to stream: Send\r\n Write to stream: FileName\r\n Write to stream: FileData \r\n Close the connection Here is the code:

        TcpClient sendClient = new TcpClient(serverName, port);
        SslStream sendStream = new SslStream(sendClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
        try
        {

            sendStream.AuthenticateAsClient(serverName, null, SslProtocols.Ssl2, true);




            sendStream.Write(Encoding.UTF8.GetBytes("Login\r\n" + username + "\r\n" + password + "\r\n"));
            sendStream.Flush();
            int bytesResp = -1;
            byte[] buffer = new byte[1026];

            bytesResp = sendStream.Read(buffer, 0, buffer.Length);

            string response = Encoding.UTF8.GetString(buffer, 0, bytesResp);

            if (response.Trim() == "OK")
            {

                byte[] fileNameByte = Encoding.UTF8.GetBytes(fileName + "\r\n");
                byte[] fileData = File.ReadAllBytes(filePath);
                  byte[] newLine = Encoding.ASCII.GetBytes("\r\n");

                byte[] clientData = new byte[4 + Encoding.ASCII.GetBytes("Send\r\n").Length + fileNameByte.Length + fileData.Length+newLine.Length];



                byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);

                byte[] send = Encoding.ASCII.GetBytes("Send\r\n");



                send.CopyTo(clientData, 0);
                fileNameLen.CopyTo(clientData, 4 + send.Length);
                fileNameByte.CopyTo(clientData, send.Length);
                fileData.CopyTo(clientData, 4 + fileNameByte.Length + send.Length);
                newLine.CopyTo(clientData, 4+ fileNameByte.Length + send.Length + fileData.Length);

                MessageBox.Show(clientData.Length.ToString());






                sendStream.Write(clientData, 0, clientData.Length);

                sendStream.Flush();
                sendStream.Write(Encoding.UTF8.GetBytes("Quit\r\n"));


                  sendClient.Close();


            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

Does anybody have an idea please?


Solution

  • You haven't told us about the other end of the connection, so this answer is partially speculative...

    BitConverter.GetBytes(fileNameByte.Length); is likely to be a little-endian conversion.

    Almost all network encoding will be big-endian, so this is a strong candidate for the failure.

    I suggest you use the EndianBitConverter.Big converter from Jon Skeet's miscutil to get the proper encoding order.