CodeGuru
Earthweb Search
Forums Wireless Jars Gamelan Developer.com
CodeGuru Navigation
RSS Feeds

RSSAll

RSSVC++/C++

RSS.NET/C#

RSSVB

See more EarthWeb Network feeds

follow us on Twitter

Member Sign In
User ID:
Password:
Remember Me:
Forgot Password?
Not a member?
Click here for more information and to register.

Become a Marketplace Partner

jobs.internet.com

internet.commerce
Partners & Affiliates
















Home >> .NET / C# >> C# >> Network & Systems >> Sockets


Communicating over Sockets: Blocking vs. Unblocking
Rating:

Mark Strawmyer (view profile)
March 24, 2006

Go to page: 1  2  Next

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


(continued)




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>

About the Author
Mark Strawmyer, MCSD, MCSE, MCDBA is a Senior Architect of .NET applications for large and mid-size organizations. Mark is a technology leader with Crowe Chizek in Indianapolis, Indiana. He specializes in architecture, design and development of Microsoft-based solutions. Mark was honored to be named a Microsoft MVP for application development with C#. You can reach Mark at mstrawmyer@crowechizek.com.

Go to page: 1  2  Next

Tools:
Add www.codeguru.com to your favorites
Add www.codeguru.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed







RATE THIS ARTICLE:   Excellent  Very Good  Average  Below Average  Poor  

(You must be signed in to rank an article. Not a member? Click here to register)

Latest Comments:
No Comments Posted.
Add a Comment:
Title:
Comment:
Pre-Formatted: Check this if you want the text to display with the formatting as typed (good for source code)



(You must be signed in to comment on an article. Not a member? Click here to register)