C# 使用 SSL 创建 TCP 客户端连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/252365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 20:02:17  来源:igfitidea点击:

Creating a TCP Client Connection with SSL

c#.netssltcp

提问by Mel Green

I'm trying to create a TCP connection and send/read data that uses SSL, but I haven't been able to successfully accomplish this.

我正在尝试创建 TCP 连接并发送/读取使用 SSL 的数据,但我无法成功完成此操作。

What I'd like to do is something like this:

我想做的是这样的:

    TcpClient _tcpClient = new TcpClient("host", 110);

    BinaryReader reader = 
       new BinaryReader(new System.Net.Security.SslStream(_tcpClient.GetStream(), true));

    Console.WriteLine(reader.ReadString());

I haven't had any luck with it though. An exception is thrown when creating the BinaryReader.

不过我没有运气。创建 BinaryReader 时抛出异常。

Does anyone know of a simple example that does this? I'm not interested in writing the server side of this, just the client.

有谁知道一个简单的例子来做到这一点?我对编写服务器端不感兴趣,只对客户端感兴趣。

采纳答案by Ovidiu Pacurar

BinaryReader reads primitive data types as binary values in a specific encoding, is that what your server sends?
If not use StreamReader:

BinaryReader 将原始数据类型读取为特定编码的二进制值,这是您的服务器发送的吗?
如果不使用 StreamReader:

TcpClient _tcpClient = new TcpClient("host", 110);

StreamReader reader = 
   new StreamReader(new System.Net.Security.SslStream(_tcpClient.GetStream(), true));

Console.WriteLine(reader.ReadToEnd());

回答by toddk

I'm not entirely sure if this will work for your application but I would recommend taking a look at stunnel:
http://www.stunnel.org

I've used it for wrapping existing TCP connections in the past.

我不完全确定这是否适用于您的应用程序,但我建议您查看 stunnel:
http: //www.stunnel.org

我过去曾用它来包装现有的 TCP 连接。