Go Back

Unit Testing Sockets

So I've been playing around with .net's network sockets a little bit for a project I'm working on. Here's a little factory pattern to generate up a send and receive socket so that you can test things.

 

  public class ClientAndServerSockets

    {

        public Socket Client;

        public Socket Server;

        /// <summary>

        /// Factory Generates a client and server socket to use in testing

        /// </summary>

        /// <returns>a client and server socket</returns>

        public static ClientAndServerSockets RetrieveSockets()

        {

            ClientAndServerSockets retval = new ClientAndServerSockets();

            Socket listener = new Socket(AddressFamily.InterNetwork,

            SocketType.Stream, ProtocolType.Tcp);

            listener.Bind(new IPEndPoint(IPAddress.Any, 4000));

            listener.Listen(20);

            IAsyncResult iarAccept = listener.BeginAccept(null, null);//begin listening

            retval.Client = new Socket(AddressFamily.InterNetwork,

            SocketType.Stream, ProtocolType.Tcp);

            IAsyncResult iarConnect = retval.Client.BeginConnect(new IPEndPoint(new IPAddress(new byte[] { 127, 0, 0, 1 }), 4000), null, null);

            retval.Server = listener.EndAccept(iarAccept);

            retval.Client.EndConnect(iarConnect);

            listener.Close();

            return retval;

        }

    }

Basically, I use Async calls to setup a listening socket then while that's on another thread doing "Accept" I do an async Connect on the other socket. I close out the listening port after I have my two connections and return them. The container class is used so that I don't have to do 'out' parameters.

Facebook DZone It! Digg It! StumbleUpon Technorati Del.icio.us NewsVine Reddit Blinklist Furl it!

Post a comment!
  1. Formatting options