CodeGuru
Earthweb Search
Forums Wireless Jars Gamelan Developer.com
CodeGuru Navigation
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
















RSS Feeds

RSSAll

RSSVC++/C++

RSS.NET/C#

RSSVB

See more EarthWeb Network feeds

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)


JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Internet.com eBook: The Pros and Cons of Outsourcing
Go Parallel Article: Scalable Parallelism with Intel(R) Threading Building Blocks
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES