I’m writing an application server that will maintain upwards of 2,000 long-term persistent client TCP connections. I’d like to know what the most efficient way to asynchronously accept the connections and read data from them is.
I essentially want to wrap all of the socket code in a class with a public footprint like this:
public partial class ApplicationClient
{
private Socket socket;
public ApplicationClient(Socket socket)
{
this.socket = socket;
}
public event ApplicationMessageEventHander MessageReceived;
private void OnMessageReceived(string message)
{
ApplicationMessageEventHander messageReceived = this.MessageReceived;
if (messageReceived != null)
{
var eventArgs = new ApplicationMessageEventArgs(message);
messageReceived(this, eventArgs);
}
}
}
What’s the best way to use .NET’s sockets to fit this architecture?
EDIT: It’s also worth mentioning that each message passed by the client will be newline-terminated. I don’t want to fire the event until the entire message has been received.
You should use the BeginReceive and EndReceive functions. They take a parameter to an AsyncCallback delegate. You will then have to write some code that wraps that to handle your new line piece, and then you should call another delegate.
I believe something like this would be the appropriate way to handle it: