Monday, January 05, 2009

TCP / IP in C#

I'm currently working on a Generic Client Server setup in C#. It uses asynchronous IO, and fires events on; connect, disconnect, message recieved, and message sent. I used testing consoles for each of the librarys (Client and Server) and was able to send packets at 10ms delay from 30 clients and the server would send packets to all connected clients at 1ms delay. I let this run for a few hours just to make sure it could handle a little bit of a load.

My plans for this server don't require very much message traffic, but I wanted to know it could handle what ever I plan on throwing at it.

Every message that is sent is prefaced with how much data is in the message, so there is no need to add "" or any other such clunky mechanism to the end of a byte[] to tell the other side when they've got the whole message.

The buffers are 1024 bytes (1Kb) using a const that can be changed if needed, and if a message is sent longer than this, the receiving side will simply make another read callback until all of the message is received.

Each connection to the server, uses an internal ID system:

class Connection
{
....
private static int LastID;
private static Queue unusedID;
private int getID()
{
if(unusedID.Count > 0)
return unusedID.dequeue();
else
return ++LastID;
}
......
private int myID;
public int ID
{
get{return myID;}
}
....
public Connection()
{
myID = getID();
....
}
private ~Connection()
{
unusedID.Enqueue(myID);
myID = 0;
....
}
....
}

No comments: