I am new in C# development. I am trying to use ssl/tls over tcp but in my code, system.net.sockets.socket (bare socket) is used not tcpclient or tcplistner. I have searched over net atleast 200 links but I didn't get anything related that. I want to use less coding and done ssl or tsll over tcp socket connection. I have client, server, ca certificate, key in .key format. Please help with example or link. You can ask questions if u feel more details.
问题:
回答1:
Why don't you want to TcpClient
? Creating a SSL connection with TcpClient
and Ssltream
is quite easy. Unless you require thousands of simultaneous connections I would stick with TcpClient
and SSLStream
.
A basic TcpClient
and SslStream
example would be as follows:
static void Main(string[] args)
{
string server = "127.0.0.1";
TcpClient client = new TcpClient(server, 443);
using (SslStream sslStream = new SslStream(client.GetStream(), false,
new RemoteCertificateValidationCallback(ValidateServerCertificate), null))
{
sslStream.AuthenticateAsClient(server);
// This is where you read and send data
}
client.Close();
}
public static bool ValidateServerCertificate(object sender, X509Certificate certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
High performance socket code can be difficult to write in .NET but there are good examples out there. You have a number of choices. I'm not sure one solution fits all so I'll list a few here.
- Using an [Asynchronous Client Socket] maybe be a good place to start
- There are a few existing libraries you can make use of. I've used Nitro/Async however I don't think it has been updated since 2009. There was talk of a version 2 but I don't believe it materialized.
- I'm not familar with it but CodeProject has C# SocketAsyncEventArgs High Performance Socket Code
- Review Microsoft's guidance, High Performance .NET Socket Server Using Async Winsock
- Read everything that Stephen Toub has to say including Awaiting Socket Operations
I didn't address SSL specifically but look into the SslStream
Class.
You'll also want to look into buffer pooling. If you're serving thousands of clients garbage collection will be a problem. An excellent introduction to this is Sunny Ahuwanya's Blog
http://nitoasync.codeplex.com/
before.
回答2:
You should be able to use System.Net.Sockets.NetworkStream
to wrap your socket and then System.Net.Security.SslStream
to wrap the network stream.
Socket socket;
Stream networkStream = new NetworkStream(socket);
Stream sslStream = new SslStream(networkStream);