Socket server with. Net 3.5 using pooled buffers and socketasynceventargs

Source: Internet
Author: User

In a previous post I talked about the system. net. sockets enhancements in. net 3.5, and if you haven't read it I suggest you do before tucking in to this as some of that code is important to understand what's happening here. before I start, in essence this is just a result of my experimentation and while it seems it does a pretty good job, i'm not going to claim it's bullerproof or that it's a good example of how to write a socket server all it does is demonstrate the techniques of working with the new clasand methods.

The sample solution you can see on the right there contains three projects. flawlesscode contains all the classes we'll need to build ourselves a socket server. testloadgenerator is a console application which generates load for us by connecting lots of sockets to our server and sending it random data. testsocketserver is a small socket server implementation using the classes in flawlesscode.

Tcpsocketlistener

We'll begin by looking at the flawlesscode project and in particle, the tcpsocketlistener. it shoshould be fairly obvious from the name what this class is meant to achieve, it sits in a loop listening for socket connections and lets us know when one arrives. the public interface is very simple and looks like this:

Public void start ();

Public void stop ();

Public event eventhandler <socketeventargs> socketconnected;

The only thing we'll take a closer look at here is the internal loop which accepts the client sockets. here you can see the first usage of the new socketasynceventargs and we're re calling acceptasync, in our callback we check the socketerror property to see if we had errors.

Private void listenforconnection (socketasynceventargs ARGs)

{

Args. acceptsocket = NULL;

Listenersocket. invokeasyncmethod (

New socketasyncmethod (listenersocket. acceptasync)

, Socketaccepted, argS );

}

Private void socketaccepted (Object sender, socketasynceventargs E)

{

Socketerror error = E. socketerror;

If (E. socketerror = socketerror. operationaborted)

Return; // server was stopped

If (E. socketerror = socketerror. Success)

{

Socket handler = E. acceptsocket;

Onsocketconnected (handler );

}

Lock (this)

{

Listenforconnection (E );

}

}

Serverconnection

Next we're re going to take a look at the serverconnection class, this class encapsulates the concept of a connected client. depending on what you wanted to do with your server you may decide to extend this class, rewrite it or maybe completely replace it with something derived from networkstream. for our purposes today, this class when created will begin listening for data from the network, it has two public methods, one to disconnect the client and one to send data synchronously back to the client. serverconnection also fires two callbacks, one when data is pinned Ed and one when the client is disconnected. here is a rundown of the interesting parts:

Public void disconnect ()

{

Lock (this)

{

Closeconnection (eventargs );

}

}

Public void senddata (byte [] data, int32 offset, int32 count)

{

Lock (this)

{

State state = eventargs. usertoken as State;

Socket socket = state. Socket;

If (socket. Connected)

Socket. Send (data, offset, Count, socketflags. None );

}

}

Private void listenfordata (socketasynceventargs ARGs)

{

Lock (this)

{

Socket socket = (ARGs. usertoken as State). Socket;

If (socket. Connected)

{

Socket. invokeasyncmethod (socket. receiveasync,

Receivedcompleted, argS );

}

}

}

Private void receivedcompleted (Object sender,

Socketasynceventargs ARGs)

{

If (ARGs. bytestransferred = 0)

{

Closeconnection (ARGs); // graceful disconnect

Return;

}

If (ARGs. socketerror! = Socketerror. Success)

{

Closeconnection (ARGs); // not graceful disconnect

Return;

}

State state = args. usertoken as State;

Byte [] DATA = new byte [args. bytestransferred];

Array. Copy (ARGs. buffer, argS. offset, Data, 0, Data. Length );

Ondatareceived (data, argS. remoteendpoint as ipendpoint,

State. datareceived );

Listenfordata (ARGs );

}

Private void closeconnection (socketasynceventargs ARGs)

{

State state = args. usertoken as State;

Socket socket = state. Socket;

Try

{

Socket. Shutdown (socketshutdown. Both );

}

Catch {} // throws if client process has already closed

Socket. Close ();

Socket = NULL;

Args. Completed-= receivedcompleted; // must remember this!

Ondisconnected (ARGs, state. disconnectedcallback );

}

Taking it from the top, we can see the public disconnect method, this simply callour internal closeconnection method which shuts down the socket and fires our disconnected callback. an interesting point to note here is that when this class is instancated we subscribe to the socketasynceventargs. completed event, when a client disconnects we need to remember to unhook this event because when we're re reusing objects and pooling resources like this it's a bad idea to leave these references hanging around. moving down we have the public senddata method, nothing interesting here really, just a standard synchrounous call. next we get to the internal loop which listens for data from the client, notice how we check socketasynceventargs. bytestransferred, if this is zero, the client has closed the connection and disconnected gracefully. we check the value of socketerror here also to make sure there was no error anywhere, after that we make a copy of the bytes we have Ed and inform any interested parties we have new data.

Bufferpool and socketargspool

These two classes help us with pooling our resources and are not really very interesting, they're also almost identical to the msdn examples so you can either look there or just check out the code.

Bufferpool: http://msdn2.microsoft.com/en-us/library/bb517542.aspx

Socketargspool: http://msdn2.microsoft.com/en-us/library/bb551675.aspx

Testsocketserver

Now that we 've sen to main functionality in the flawlesscode project we're re going to look at a simple socket server implementation using these classes.

Tcpsocketlistener socketlistener = new tcpsocketlistener (IPaddress. Any, 12345, 10 );

Socketlistener. socketconnected + = socketlistener_socketconnected;

Socketlistener. Start ();

Fairly straight forward, we fire up out listener on port 12345 and give the listening socket an allowed connection backlog of 10.

Static void socketlistener_socketconnected (Object sender, socketeventargs E)

{

Socketasynceventargs ARGs = socketargspool. Checkout ();

Buffermanager. Checkout (ARGs );

Serverconnection connection = new serverconnection (E. socket, argS,

New datareceivedcallback (datareceived ),

New disconnectedcallback (disconnected ));

}

When a client connects we get an socketasynceventargs and some free buffer space for our client and then we create an instance of serverconnection. note that we are passing delegates into the constructor, this is because the serverconnection begins listening for data immediately and we have to have the callbacks hooked up before hand. if we let the call to the constructor complete and the we hooked To standard events we may have already missed the first batch of Data!

Static void datareceived (serverconnection sender, dataeventargs E)

{

// Do whatever we want here...

}

Static void disconnected (serverconnection sender, socketasynceventargs E)

{

Buffermanager. checkin (E );

Socketargspool. checkin (E );

}

Here we do whatever processing is necessary when a client sends us data. When a client disconnects we just check our buffer space and socketasynceventargs back into their respective pools to fight another day.

Testloadgenerator

I'm not going to go into how the load generation works for now, the code is all very straight forward if you 've managed to follow the post this far I wowould imagine. one thing to note is that if you want to test this code and open thousands of connections you need to tweak a registry setting or Windows wont give you enough ports. you will need to add the DWORD maxuserport to HKLM \ System \ currentcontr Olset \ Services \ Tcpip \ Parameters and give it a high enough value that windows won't run out of ports (reboot required, sorry )! Here is a quick examaple of how the load generation classes are used:

Static void main (string [] ARGs)

{

Loadgenerator generator = new loadgenerator (15000 );

Generator. bytes sperdelivery = 2048;

Generator. deliveriespersecond = 2;

Generator. Fig = 15000;

Generator. socketdelay = 5;

Generator. socketsperdelivery = 3;

Generator. Start (IPaddress. parse ("127.0.0.1"), 12345 );

Console. Readline ();

Generator. Stop ();

}

Pretty easy to use, right? We create an instance of the loadgenerator class, telling it we 'd like 15,000 connections maximum. then we set some properties saying that we 'd like each connected socket to deliver 2 K of data twice per second. we 'd like 15,000 sockets and we 'd like them to connect 5 ms apart and that we want on average 3% of sockets to send data in each delivery. then we just aim and fire! Check it out:

When this was taken, the server executable was using 109 MB or RAM and 1% CPU on my desktop machine so I think at 15,000 connections we 've got some pretty damned good performance out of this thing! Obviusly when we start implementing the server logic and actually processing each packet this will go up, but for a bare socket server, I'm pretty pleased.

Net35socketserver.zip (24.77 KB)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.