C#: SSL with SocketAsyncEventArgs? - c#

I'm developing a socket server using C# .NET. I'm using the async model provided by the SocketAsyncEventArgs class, because it must be a high performance server to support many connections in short periods of time. Next, I want to secure the communication between
clients and server, and I think I could use SSL.
Is there any way of using SSL with the SocketAsyncEventArgs model? I know .NET has the SslStream class for SSL securing, but I need to use SocketAsyncEventArgs for high performance.
Is it possible to use SSL in an upper level, without implementing it in the server code?
Thanks in advance.

Not sure if anyone cares anymore since this is so old but I needed to do just that this week and could not find anything on the internet that met my needs. Maybe there is something new in the framework that does this that I was unable find... Regardless, I would post source code but since I wrote it for my company and they tend to frown on that, I'll just outline the approach I took:
Since SslStream takes a stream in the constructor, I implemented my own Stream subtype with an underlying MemoryStream for reads and another for writes. I also pass in the TcpClient to this object as well.
I used the TcpClient to do the handshake for setting up the SSL connection. After authenticating the server or client depending on how I am using it, I then use my two MemoryStreams for the SslStream read/writes.
So for Async writes, I first write my payload to the SslStream which populates my MemoryStream for writing with encrypted data. With the encrypted data from the MemoryStream, I populate the SocketAsyncEventArgs buffer and call the TcpClient SendAsync method. For reads, it's pretty much the opposite.
I can't say it particular excites me to move the data like that but as long as you don't let your MemoryBuffer objects get reallocated constantly, it's not a performance issue. At least this way, I can use just the framework and my own code without relying on third party software.

You can take third-party implementation of SSL/TLS protocol, such as our SecureBlackbox, and use it with any transport, including .NET Sockets in asynchronous mode. SSL server component of SecureBlackbox doesn't have it's own socket, instead it fires events, in whose handlers you write your socket-related code. This way you an plug any transport, even non-socket one.

I think I may have found a project that provides this.
https://sourceforge.net/projects/socketservers/
I'm still playing with it and am bumping into an issue loading the server certificate, however, looking through the source code it looks promising.
One aspect I'm unsure about is that it p/invokes to secur32.dll rather than being a pure c# implementation, so I'm not sure what the memory/performance impact of that is.
The details on the sourceforge project page are sparse as to what the goal of the project is.

Related

Faking IO Streams

As part of my student group's hobby project, I'm creating a simulation of a wired network of microcontrollers in order to test the algorithms we've written. Each controller is wired up to several data ports, which each have an input and output stream. I'm modeling this relationship by giving each port a BinaryReader and BinaryWriter, each backed by its own MemoryStream. However, I ran into a snag when trying to 'connect' ports between different controllers. Simulating the latency is outside the scope of this iteration of the simulation, so I just needed to link them directly somehow.
So my question is this: how can I fake an IO stream like this using two different BinaryReader/BinaryWriter or MemoryStream sets, such that when I write to one the other can immediately read it?
I ended up using UDP sockets connected to each other via the loopback address, which simulated the asynchronous nature of the network well without dealing with latency issues.
I'm not allowed to publish the actual code, but the implementation was fairly straightforward. Each data port has its own UdpClient from the System.Net.Sockets namespace and a randomly assigned UDP port. An update loop iterates over each port and calls the udpClient.Send() and udpClient.Receive() functions as appropriate, using a simple byte[] buffer to handle incomplete messages. I think an overview of high-level networking in .Net is outside the scope of this question, but there's some nice resources available on MSDN just a Google search away.

Is WebClient the best way to download http data?

Problem: I need to download hundreds of images from different hosts. Each host has anywhere between 20-hundreds of images.
Solution: using a new WebClient every time a image needs to be downloaded through the WebClient's DownloadData method.
Or would be better to keep a pool of open socket connections and making the http request using lower level calls?
Is it expensive to open/close a tcp connection (I'm assuming that is what WebClient does), so that using a pools sounds more efficient?
I believe the underlying infrastructure which WebClient uses will already pool HTTP connections, so there's no need to do this. You may want to check using something like Wireshark of course, with some sample URLs.
Fundamentally, I'd take the same approach to this as with other programming tasks - write the code in the simplest way that works, and then check whether it performs well enough for your needs. If it does, you're done. If it doesn't, use appropriate tools (network analyzers etc) to work out why it's not performing well enough, and use more complicated code only if it fixes the problem.
My experience is that WebClient is fine if it doesn't what you need - but it doesn't give you quite as much fine-grained control as WebRequest. If you don't need that control, go with WebClient.
I use HttpWebRequest and HttpWebResponse to scrape anything I want. Unless, of course, there are services available for the requirement, but even though, sometimes, there are limitations (business limitations) and I often prefer to dig the html from pure http request. Sometimes just make feel more like developer, you know...

How to send information fast like many games do?

I'm thinking like the methods games like Counter Sstrike, WoW etc uses. In CS you often have just like 50 ping, is there any way to send information to an online MySQL database at that speed?
Currently I'm using an online PHP script which my program requests, but this is really slow, because the program first has to send headers and post-information to it, and then retrieve the result as an ordinary webpage.
There really have to be any easier, faster way of doing this? I've heard about TCP/IP, is this what I should use here? Is it possible for it to connect to the database in a faster way than indirectly via the PHP script?
TCP/IP is made up of three protocols:
TCP
UDP
ICMP
ICMP is what you are using when you ping another computer on a network.
Games, like CounterStrike, don't care about what you previously did. So there's no requirement for completeness, to be able to reconstruct what you did (which is why competitors have to tape what they are doing). This is what UDP is used for - there's no guarantee that data is delivered or received. Which is why lag can be such a problem - you're already dead, you just didn't know it.
TCP guarantees that data is sent and received. Slower than UDP.
There are numerous things to be aware of to have a fast connection - less hops, etc.
Client-to-server for latency-critical stuff? Use non-blocking UDP.
For reliable stuff that can be a little slower, if you use TCP make sure you do so in a non-blocking fashion (select(), non-blocking send, etc.).
The big reason to use UDP is if you have time-sensitive data - if the position of a critter gets dropped, you're better off ignoring it and sending the next position packet rather than re-sending the last one.
And I don't think any high-performance game has each and every call resolve to a call to the database. It's more common to (if a database is even used) persist data occasionally, or at important events.
You're not going to implement Counterstrike or anything similar on top of http.
Most games like the ones you cite use UDP for this (one of the TCP/IP suite of protocols.) UDP is chosen over TCP for this application since it's lighter weight allowing for better performance and TCP's reliability features aren't necessary.
Keep in mind though, those games have standalone clients and servers usually written in C or C++. If your application is browser-based and you're trying to do this over HTTP then use a long-lived connection and strip back the headers as much as possible, including cookies. The Tornado framework may be of interest to you there. You may also want to look into HTML5 WebSockets however widespread support is still a fair way off.
If you are targeting a browser-based plugin like Flash, Java, SilverLight then you may be able to use UDP but I don't know enough about those platforms to confirm.
Edit:
Also worth mentioning: once your networking code and protocol is sufficiently optimized there are still things you can do to improve the experience for players with high pings.

transferring files using TCP

I'm to trying to develop a program to transfer files using TCP (in a local network) with C#, files should be transfer in encrypted way.
My knowledge about c# is average, and about socket programming just know the basics.
Currently have no idea how to begin.It will be great if you have any suggestion about how to begin, if there is any book, website or any other resources.
You could use WCF with netTcpBinding.
This would encrypt the file during transfer and reduce the development effort, since you do not need to program any low level sockets code.
Unless you want to use it as a learning experience for C#/.NET socket programming, there are a lot of free FTP apis that will do it for you without the pain of having to reinvent the wheel. Indy has been going for almost a decade and the others are fairly stable.
TCP sockets are pretty easy to use. While I don't know the API in c#, it will undoubtedly support a send() method, where you can pass in the bytes of your file, and on the other side it will let you register a callback function that will be called when bytes are received. The TCP protocol guarantees that the data passed in-between will not be corrupted or lost. You will need to encrypt and decrypt the data yourself however.
The easiest way to begin is to code up a 2-client chat program where you send the messages using TCP. If you want to understand more about the TCP protocol and the "network stack" (a set of underlying protocols) then you can start on wikipedia and carry on with a decent book on networks - it is actually a very big topic, but you don't really need to know unless you are making a serious app.
By the way, an easy linux hack is to use netcat (type man nc to get help).

TcpClient.GetStream().Read() vs. TcpClient.Client.Receive()

.NET allows two very similar ways to "read" from the network (assuming TCP connection):
1. TcpClient.GetStream().Read()
2. TcpClient.Client.Receive()
By looking at NetworkStream source code - it seems that it's an extra wrapper over the underlying socket, which eventually calls Socket methods.
Question: what's the benefit of using "indirect" NetworkStream variation (#1), instead of using direct wrapper provided by Socket implementation?
Thank you,
Boris.
There is, in fact, a pretty clear benefit of using the first option (TcpStream and not Socket). The benefit is that stream API is more flexible when different underlying implementations are needed at for the same program.
For example, a code which sometimes may use SSL and sometimes may not use it, can switch between SslStream and TcpStream with no changes to the calling code. This is something which is much harder to accomplish using only plain Socket API.
Nothing, really. It's just that sometimes it's more convenient to use a Stream.
To me, a successful Socket.Receive operation with zero bytes received tells you that connection is closed.

Categories