这是我的代码,用于发送以 SSL 编码的 TCP 请求并从服务器获取答案,但它不起作用。调试和 try catch 异常都没有用。
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));
}
我是从 stackoverflow 的回答中得到的,所以我很惊讶它不起作用。这是我从服务器接收问候语的代码(它工作正常):
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());
最佳答案
如果 sslStream.Read(buffer, 0, buffer.Length);
挂起,那是因为服务器没有发送响应。
看看你在 github 上的代码(链接自你的其他问题),看起来你正在使用 Console.ReadLine()
来读取命令,然后将它们写入你的网络流。
发生的事情是 ReadLine()
剥离了它返回的字符串中的 "\r\n"
,所以当发送给服务器就是加回"\r\n"
,让服务器知道命令执行完毕(它会等到EOL序列才会响应)。
你可以做的是在 SendRequest()
中,你可以做:
sslStream.Write(Encoding.ASCII.GetBytes(request + "\r\n"));
关于C# 通过 TCP 使用 SSL 发送请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24713407/