Communicating over Sockets: Blocking vs. Unblocking

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 =
         IPEndPoint myEndPoint =
            new IPEndPoint(localMachineInfo.AddressList[0],

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

         Console.WriteLine("Listening on port " +
         acceptThread = new Thread(AcceptConnections);
         acceptThread.IsBackground = true;

      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;

            // 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();
            while (true)
               int bytesRead = connection.Socket.Receive(buffer);
               if (bytesRead > 0)

                  // Parse the message
                  XmlDocument xmlInput = new XmlDocument();

                  // Send back a preset response based on the type
                  XmlDocument xmlOutput = new XmlDocument();
                  if (xmlInput.DocumentElement.Name.Equals("uptime"))
                     // Logic to generate desired exception here
               else if (bytesRead == 0) return;
         catch (SocketException socketExec)
            Console.WriteLine("Socket exception: " +
         catch (Exception exception)
            Console.WriteLine("Exception: " + exception);
            lock (this.connections)

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);

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

   <description>System uptime</description >

More by Author

Must Read