0

Im try to read an xml file and send to server with sslStream. Before send to server i must make Login and after succesfull authorization i must send the fileData. To fileSize is about 300kb. I can make sycessfull the login, but the problem is that server seems to not receive the data that i send. here is the code method1: I suceesfull make login(i receive ok but it seems that i can't send the contents of xml file)

TcpClient sendClient = new TcpClient(serverName, port);
        SslStream sendStream = new SslStream(sendClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
        sendStream.AuthenticateAsClient(serverName, null, SslProtocols.Ssl2, true);

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

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

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

        if (response.Trim() == "OK")
        {
            MessageBox.Show("Connected");
            byte[] b1 = File.ReadAllBytes(filePath);
            sendStream.Write(Encoding.UTF8.GetBytes("Send\r\n"));
            sendStream.Write(Encoding.UTF8.GetBytes(fileName+"\r\n"));
            sendStream.Write(b1, 0, b1.Length);
            sendStream.Flush();
            sendStream.Write(Encoding.UTF8.GetBytes("Quit\r\n"));
            sendStream.Flush();
            sendClient.Close();
        }

and here is a second method with streamWriter

TcpClient sendClient = new TcpClient(serverName, port);
        SslStream sendStream = new SslStream(sendClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
        sendStream.AuthenticateAsClient(serverName, null, SslProtocols.Ssl2, true);

        StreamWriter writer = new StreamWriter(sendStream);
        writer.WriteLine("Login");
        writer.WriteLine(username);
        writer.WriteLine(password);
        writer.Flush();
        StreamReader reader = new StreamReader(sendStream);
        string response = reader.ReadLine();
        if (response.Trim() == "OK")
        {
            MessageBox.Show("succesfull connect");

            string allText = File.ReadAllText(filePath,Encoding.Default);
            writer.WriteLine("Send");
            writer.WriteLine(fileName);
            writer.WriteLine(allText);
            sendClient.Close();
        }
user1654278
  • 67
  • 1
  • 10
  • Server code is needed. – Oguz Ozgul Nov 26 '15 at 12:56
  • Unforunately there is no information about the server code – user1654278 Nov 26 '15 at 13:07
  • How do you know that the data is not received by the server? – Oguz Ozgul Nov 26 '15 at 13:26
  • after server receives the data, it sends me an email. Iknow it because i have one old implementation with Delphi wich uses Indy Sockets and OpenSsl – user1654278 Nov 26 '15 at 13:42
  • So what response do you get then, you just close the sendClient after posting the data. Is there any documentation for the server? Is it expecting the data with this format (Send\r\n\r\n) ? May be it receives the data but cannot send the e-mail? HAve you checked the server logs? – Oguz Ozgul Nov 26 '15 at 13:44
  • When i want to send data i do't wait any response. I must close the connection according to instructions i have. I wait response only when i make login ('ok') and when i want to receive data when i write to stream the command 'Get'. The last two operations works fine – user1654278 Nov 26 '15 at 14:02
  • Then you should definitely check the server logs for any errors. You can also check through your favorite network sniffer if the file data is sent to the server. There is no reason to believe that it's not. You either don't send the data as the server expects, or the server has another kind of problem, or, since you immediately close the socket, may be this is casuing the server to fail. Please see server logs. – Oguz Ozgul Nov 26 '15 at 14:25
  • The problem is that i have not access to server logs. I have no other information about the server – user1654278 Nov 26 '15 at 14:35
  • Someone must be maintaining that server. Contact them. – Oguz Ozgul Nov 26 '15 at 14:44

2 Answers2

0

Ok, one solution is to write all commands as a byte array and copy these to a bigger array. The trick is to add the dataSize as a bigendian number

user1654278
  • 67
  • 1
  • 10
0

Do not doubt that the answer to your question is this code

public System.Net.Security.SslStream GetStream(NetworkStream _NetworkStream)
        {
            try
            {
                System.Net.Security.SslStream sslStream = new System.Net.Security.SslStream(_NetworkStream, false);
                sslStream.AuthenticateAsServer(serverCertificate, clientCertificateRequired: false,
                enabledSslProtocols:
                    System.Security.Authentication.SslProtocols.Default |
                    System.Security.Authentication.SslProtocols.None |
                    System.Security.Authentication.SslProtocols.Tls |
                    System.Security.Authentication.SslProtocols.Tls11 |
                    System.Security.Authentication.SslProtocols.Tls12 |
                    System.Security.Authentication.SslProtocols.Ssl2 |
                    System.Security.Authentication.SslProtocols.Ssl3
                , checkCertificateRevocation: true);
                new SSL().DisplaySecurityLevel(sslStream);
                new SSL().DisplaySecurityServices(sslStream);
                new SSL().DisplayCertificateInformation(sslStream);
                new SSL().DisplayStreamProperties(sslStream);
                sslStream.ReadTimeout = 5000;
                sslStream.WriteTimeout = 5000;
                return sslStream;
            }
            catch (Exception ex)
            {
                
                throw ex;
            }
            
        }
public string ReadMessage(System.Net.Security.SslStream sslStream)
        {
            // Read the  message sent by the client.
            // The client signals the end of the message using the
            // "<EOF>" marker.
            byte[] buffer = new byte[2048];
            StringBuilder messageData = new StringBuilder();
            int bytes = -1;
            //do
            //{
            // Read the client's test message.
            bytes = sslStream.Read(buffer, 0, buffer.Length);

            // Use Decoder class to convert from bytes to UTF8
            // in case a character spans two buffers.
            Decoder decoder = Encoding.UTF8.GetDecoder();
            char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
            decoder.GetChars(buffer, 0, bytes, chars, 0);
            messageData.Append(chars);
            // Check for EOF or an empty message.
            if (messageData.ToString().IndexOf("<EOF>") != -1)
            {
                //break;
            }
            //} while (bytes != 0);

            return messageData.ToString();
        }
        public void DisplaySecurityLevel(System.Net.Security.SslStream stream)
        {
            Console.WriteLine("Cipher: {0} strength {1}", stream.CipherAlgorithm, stream.CipherStrength);
            Console.WriteLine("Hash: {0} strength {1}", stream.HashAlgorithm, stream.HashStrength);
            Console.WriteLine("Key exchange: {0} strength {1}", stream.KeyExchangeAlgorithm, stream.KeyExchangeStrength);
            Console.WriteLine("Protocol: {0}", stream.SslProtocol);
        }
        public void DisplaySecurityServices(System.Net.Security.SslStream stream)
        {
            Console.WriteLine("Is authenticated: {0} as server? {1}", stream.IsAuthenticated, stream.IsServer);
            Console.WriteLine("IsSigned: {0}", stream.IsSigned);
            Console.WriteLine("Is Encrypted: {0}", stream.IsEncrypted);
        }
        public void DisplayStreamProperties(System.Net.Security.SslStream stream)
        {
            Console.WriteLine("Can read: {0}, write {1}", stream.CanRead, stream.CanWrite);
            Console.WriteLine("Can timeout: {0}", stream.CanTimeout);
        }
        public void DisplayCertificateInformation(System.Net.Security.SslStream stream)
        {
            Console.WriteLine("Certificate revocation list checked: {0}", stream.CheckCertRevocationStatus);

            System.Security.Cryptography.X509Certificates.X509Certificate localCertificate = stream.LocalCertificate;
            if (stream.LocalCertificate != null)
            {
                Console.WriteLine("Local cert was issued to {0} and is valid from {1} until {2}.",
                    localCertificate.Subject,
                    localCertificate.GetEffectiveDateString(),
                    localCertificate.GetExpirationDateString());
            }
            else
            {
                Console.WriteLine("Local certificate is null.");
            }
            // Display the properties of the client's certificate.
            System.Security.Cryptography.X509Certificates.X509Certificate remoteCertificate = stream.RemoteCertificate;
            if (stream.RemoteCertificate != null)
            {
                Console.WriteLine("Remote cert was issued to {0} and is valid from {1} until {2}.",
                    remoteCertificate.Subject,
                    remoteCertificate.GetEffectiveDateString(),
                    remoteCertificate.GetExpirationDateString());
            }
            else
            {
                Console.WriteLine("Remote certificate is null.");
            }
        }
  • A wall of code with no explanation is not good answer, comments in the code notwithstanding. Please add additional details that will help others understand how this addresses the question asked. You can find more information on [how to write good answers](https://stackoverflow.com/help/how-to-answer) in the help center. – Vijay Varadan Dec 23 '22 at 20:37