Communicating over Sockets: Blocking vs. Unblocking

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Welcome to this installment of the .NET Nuts & Bolts column. One of the prior articles—”Multithreading in .NET Applications, Part 3“—contained a sample multithreaded listener application and client. I’ve received a fair number of questions surrounding this and requesting more specifics about socket communication. The focus of this article will be to address the topic of sockets in more detail. Specifically, it will focus on blocking versus unblocking sockets. As an added bonus, the solution will include the use of generics and a sample socket connection pool.

Sample Task

To effectively illustrate this topic, you’ll need a sample task to perform. The sample task involves creating a socket-based communicator for sending data to a 3rd party system. For the sake of this example, assume the third-party system accepts connections on a specified port number and takes requests in the form of XML fragments and responds in kind. Once a socket connection is opened, it remains opened until it times out due to inactivity, the client closes the connection, or the 3rd party system is shut down. There are a predetermined number of XML fragments that have been identified and serve as business methods for calling into the 3rd party system.

Sample Threaded Server

You’ll create a sample threaded server to emulate the behavior of the 3rd party application with which you are going to exchange information. In this case, it will only expose a single method of “uptime,” which will accept an XML request of <uptime></uptime> and respond with the amount of time the system has been alive. Any other requests will generate an exception.

Sample Threaded Server

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Xml;

namespace CodeGuru.SocketSample
{
   /// <summary>
   /// Sample Server to emmulate a 3rd party server that uses sockets.
   /// </summary>
   class ThreadedServer
   {
      class ConnectionInfo
      {
         public Socket Socket;
         public Thread Thread;
      }

      private int portNumber;
      private List<ConnectionInfo> connections =
         new List<ConnectionInfo>();
      private Thread acceptThread;
      private Socket serverSocket;

      public ThreadedServer(int port)
      {
         this.portNumber = port;
      }

      public void Start()
      {
         // Set up the socket
         // Resolving local machine information
         IPHostEntry localMachineInfo =
            Dns.GetHostEntry(Dns.GetHostName());
         IPEndPoint myEndPoint =
            new IPEndPoint(localMachineInfo.AddressList[0],
                           this.portNumber);

         // Create the socket, bind it, and start listening
         serverSocket =
            new Socket(myEndPoint.Address.AddressFamily,
                       SocketType.Stream, ProtocolType.Tcp);
         serverSocket.Bind(myEndPoint);
         serverSocket.Listen((int)SocketOptionName.MaxConnections);

         Console.WriteLine("Listening on port " +
                           this.portNumber.ToString());
         acceptThread = new Thread(AcceptConnections);
         acceptThread.IsBackground = true;
         acceptThread.Start();
      }

      private void AcceptConnections()
      {
         while (true)
         {
            // Accept a connection
            Socket socket = serverSocket.Accept();
            ConnectionInfo connection = new ConnectionInfo();
            connection.Socket = socket;

            // Create the thread for the receive.
            connection.Thread = new Thread(ProcessConnection);
            connection.Thread.IsBackground = true;
            connection.Thread.Start(connection);

            // Store the socket in the open connections
            lock (this.connections) this.connections.Add(connection);
         }
      }

      private void ProcessConnection(object stats)
      {
         ConnectionInfo connection = (ConnectionInfo)stats;
         byte[] buffer = new byte[4000];
         System.Text.StringBuilder input =
            new System.Text.StringBuilder();
         try
         {
            while (true)
            {
               int bytesRead = connection.Socket.Receive(buffer);
               if (bytesRead > 0)
               {
                  input.Append(System.Text.Encoding.ASCII.
                               GetString(buffer));

                  // Parse the message
                  XmlDocument xmlInput = new XmlDocument();
                  xmlInput.LoadXml(input.ToString());

                  // Send back a preset response based on the type
                  XmlDocument xmlOutput = new XmlDocument();
                  if (xmlInput.DocumentElement.Name.Equals("uptime"))
                  {
                     xmlOutput.Load(@"C:uptimeresponse.xml");
                  }
                  else
                  {
                     // Logic to generate desired exception here
                  }
                  connection.Socket.Send(System.Text.Encoding.
                                         ASCII.GetBytes(
                                          xmlOutput.DocumentElement.
                                          OuterXml));
               }
               else if (bytesRead == 0) return;
            }
         }
         catch (SocketException socketExec)
         {
            Console.WriteLine("Socket exception: " +
                              socketExec.SocketErrorCode);
         }
         catch (Exception exception)
         {
            Console.WriteLine("Exception: " + exception);
         }
         finally
         {
            connection.Socket.Close();
            lock (this.connections)
               this.connections.Remove(connection);
         }
      }
   }
}

Now that you’ve created your class to provide a threaded server, you create a console application to start an instance of it. The main method contains the following code to start an instance of the server for testing:

ThreadedServer ts = new ThreadedServer(8080);
ts.Start();
Console.ReadLine();

Here is the sample XML document to be used as the return from the server:

<uptime>
   <description>System uptime</description >
   <Status>
      <code>OK</code>
      <command>uptime</command>
      <duration>0.127</duration>
      <Times>
         <submitted>20060320151107.409</submitted>
         <completed>20060320151107.566</completed>
      </Times>
   </Status>
</uptime>

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read