简体   繁体   中英

C# Sending request with SSL via TCP doesn't work

here is my code to send TCP request coded in SSL and get the answer from server, but it doesn't work. Debugging and trying to catch exceptions didn't work.

public void SendRequest(string request)
{
    byte[] buffer = new byte[2048];
    int bytes = -1;

    sslStream.Write(Encoding.ASCII.GetBytes(request));
    bytes = sslStream.Read(buffer, 0, buffer.Length);
    Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytes));
}

I took that from stackoverflow answer so I'm suprised it doesn't work. Here is my code that receives greeting from server (it works properly):

byte[] buffer = new byte[2048];
StringBuilder messageData = new StringBuilder();
int bytes = 0;
bytes = sslStream.Read(buffer, 0, buffer.Length);
Decoder decoder = Encoding.UTF8.GetDecoder();
char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
decoder.GetChars(buffer, 0, bytes, chars, 0);
messageData.Append(chars);

Console.Write(messageData.ToString());

If the sslStream.Read(buffer, 0, buffer.Length); is hanging, it's because the server hasn't sent a response.

Taking a look at your code on github (linked from your other question), it looks like you are using Console.ReadLine() to read commands and then write them to your network stream.

What is happening is that ReadLine() strips off the "\\r\\n" in the string that it returns, so what you'll need to do when sending it to the server is to add back the "\\r\\n" so that the server knows that the command is finished (it waits until it gets an EOL sequence before it will respond).

What you could do is in SendRequest() , you could do:

sslStream.Write(Encoding.ASCII.GetBytes(request + "\r\n"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM