Asynchronous Socket Programming in C#: Part I

Objective

The objective of this article is to demonstrate a socket-based client/server application that will allow two-way asynchronous communication between a server and multiple client applications. Because this example uses asynchronous methods, the server application does not use threads to communicate to multiple clients (although internally the asynchronous communication mechanism uses threads at the OS level).

The Difference Between Synchronous and Asynchronous Communication in Network Programming

The key difference between synchronous and asynchronous communication can be explained with an example.

Consider a server application that is listening on a specific port to get data from clients. In synchronous receiving, while the server is waiting to receive data from a client, if the stream is empty the main thread will block until the request for data is satisfied. Hence, the server cannot do anything else until it receives data from the client. If another client attempts to connect to the server at that time, the server cannot process that request because it is blocked on the first client. This behavior is not acceptable for a real-world application where we need to support multiple clients at the same time.

In asynchronous communication, while the server is listening or receiving data from a client, it can still process connection requests from other clients as well as receive data from those clients. When a server is receiving asynchronously, a separate thread (at the OS level) listens on the socket and will invoke a callback function (specified when the asynchronous listening was commenced) when a socket event occurs. This callback function in turn will respond and process that socket event. For example, if the remote program writes some data to the socket, a "read data event" (callback function you specify) is invoked; it knows how to read the data from the socket at that point.

Even though this could be achieved by running multiple threads, the C# and .NET frameworks provide a rich set of functionalities to do asynchronous communications without introducing the complexity of threading.

Socket Class

The Socket class ( System.Net.Sockets.Socket ) provides a set of synchronous and asynchronous methods for synchronous or asynchronous communication. As per the .NET naming convention, all the asynchronous method names are created by prefixing the words "Begin" or "End" to the name of the synchronous methods. The methods prefixed with "Begin" and "End" represent a pair of asynchronous methods corresponding to a single synchronous method, as shown in the following table.

Synchronous Methods Asynchronous Methods
Connect()
BeginConnect()
EndConnect()
Receive()
BeginReceive()
EndReceive()

Example Application

The example shown in this article has two classes, one implementing the Socket Server and the other implementing the Socket Client.

Socket Server Implementation
Figure 1

The Socket Server application is implemented in the SocketServer class (file name SocketServer.cs). This class has a main Socket object (m_mainSocket) and an array of worker Socket objects (m_workerSocket) as members. The main Socket object does the listening for the clients. Once a client is connected, the main Socket transfers the responsibility to process the transactions related to that particular client to a worker Socket. Then, the main Socket goes back and continues listening for other clients.

BeginAccept() and BeginReceive() are the two important methods in the Socket class used by the Socket Server application.

The BeginAccept() method has the following signature:

public IAsyncResult BeginAccept(
   AsyncCallback callback,    // (1) Function to call when a client
                              //     is connected
   object state               // (2) State object to preserve socket
                              //     info
);

Essentially, after calling the Listen() method of the main Socket object, you call this asynchronous method and specify a call back function (1), which you designated to do the further processing related to the client connection. The state object (2) can be null in this particular instance.

Because this is an asynchronous method, it will return immediately and the server main thread is free to process other events. Behind the scenes, a separate thread will start listening on that particular socket for client connections. When a client requests a connection, the callback function you specified will be invoked.

Inside the callback function (in the example, the function is named "OnClientConnect()"), you will do further processing related to the client connection.

public void OnClientConnect(IAsyncResult asyn)
{
   try
   {
      // Here we complete/end the BeginAccept() asynchronous call
      // by calling EndAccept() - which returns the reference to
      // a new Socket object
      m_workerSocket[m_clientCount] = m_mainSocket.EndAccept (asyn);
      // Let the worker Socket do the further processing for the
      // just connected client
      WaitForData(m_workerSocket[m_clientCount]);
      // Now increment the client count
      ++m_clientCount;
      // Display this client connection as a status message on the GUI
      String str = String.Format("Client # {0} connected",
                                 m_clientCount);
      textBoxMsg.Text = str;

      // Since the main Socket is now free, it can go back and wait
      // for other clients who are attempting to connect
      m_mainSocket.BeginAccept(new AsyncCallback
                              ( OnClientConnect ),null);
   }
   catch(ObjectDisposedException)
   {
      System.Diagnostics.Debugger.Log(0,"1","\n OnClientConnection:
                                      Socket has been closed\n");
   }
   catch(SocketException se)
   {
      MessageBox.Show ( se.Message );
   }

}

The first thing you do inside the "OnClientConnect()" function is to call the EndAccept() method on the m_mainSocket member object, which will return a reference to another socket object. You set this object reference to one of the members of the array of Socket object references you have (m_workerSocket) and also increment the client counter. Now, because you have a reference to a new socket object that now can do the further transaction with the client, the main Socket (m_mainSocket) is free; hence, you will call its BeginAccept() method again to start waiting for connection requests from other clients.

On the worker socket, you use a similar strategy to receive the data from the client. In place of calling BeginAccept() and EndAccept(), here you call BeginReceive() and EndReceive(). This, in a nutshell, is the Socket Server implementation. While you are sending out data to the clients, the server simply uses the specific worker socket objects to send data to each client.

Socket Client Implementation
Figure 1

The Socket Client application is implemented in the SocketClient class (file name SocketClient.cs). Compared to the server where you have a main Socket and an array of worker Sockets, here you only have a single Socket object (m_clientSocket).

The two important methods in Socket class used by the Socket Client application are the Connect() and BeginReceive() methods. Connect() is a synchronous method and is called to connect to a server that is listening for client connections. Because this call will succeed/fail immediately, depending on whether there is an active server listening or not at the specified IP and Port number, a synchronous method is okay for this purpose.

Once a connection is established, you call the BeginReceive() asynchronous function to wait for any socket write activity by the server. Here, if you call a synchronous method, the main thread on the client application will block and you will not be able to send any data to the server while the client is waiting for data from the server.

When there is any write activity on the socket from the server end, the internal thread started by BeginReceive() will invoke the callback function ("OnDataReceived()" in this case), which will take care of the further processing of the data written by the server.

When sending the data to the server, you just call the Send() method on the m_clientSocket object, which will synchronously write the data to the socket.

That is all there is for asynchronous socket communication using multiple clients.

Limitations/Possible Improvements

  • Up to 10 simultaneous clients are supported. You can easily modify and support unlimited number of clients by using a HashTable instead of an array.
  • For simplicity, when the server sends out a message, it is broadcast to all the connected clients. This could easily be modified to send messages to specific clients by using the Socket object pertaining to that particular client.
  • When a client is disconnected, proper action is not taken; the client count is not decremented. The correct way would be to reuse or release resources for other client connections.

Acknowledgement

Even though the content of this article is independently developed, the example program used is influenced by the article on Socket Programming in C# by Ashish Dhar.
Update added on 03/01/2005

For a more comprehensive example covering topics such as thread synchronization, please see Part II of this article.

About the Author

Jayan Nair

Jayan Nair is a Senior Software Engineer with 15+ years of experience working with cutting edge software technologies. Currently he is developing the next generation software applications for the telecommnunications testing industry. Jayan's passions: Object Oriented software design and developing reusable software components. His motto: "if the software you write is not reusable, you are not writing software, but hardware instead". Jayan finished his Masters degree in Computer Science from Virginia Tech, Blacksburg, VA. His expertise includes, C, C++, Java, J2EE, Visual Basic, C#, ASP.NET and distributed applications. He is also a Sun Certified Programmer for the Java Platform (SCPJ). You can contact him at jnair1998@hotmail.com.

Related Articles

Downloads

IT Offers

Comments

  • Lightweight perceptive – Nike Let off TR Right in spring 2013 3 series

    Posted by Tufffruntee on 04/24/2013 02:46pm

    Nike Emancipated TR Fit 3 prominent features is to use the new scheme: Nike On the loose 5 soles improved bending Groove; supplemental tractor pattern making training more focused when; lighter ballast, the permeability is stronger, and more smart shoe designs not lone order shoes [url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache[/url] more serene wearing, barefoot training caress, but also more stylish appearance. Nike Manumitted TR Fitting 3 provides unequalled lateral stability, you can deceive the legs in the lap boost during training. Eager vamp nobles breathable grate, lower suds's solitary delineate can be [url=http://markwarren.org.uk/property-waet.cfm]nike air max 90[/url] seen under the aegis it. Lightweight, demanding, reduce froth material familiar by very only one seams, more amenable, advocate is stronger. Need more help, department of a training utilize, foam make inaccessible in more parts of the shortage in return agreeableness, foam loose. Throw away two-ply say nothing moisture wicking counterfeit materials, flat on your feet, hands maintain feet dry and comfortable. Phylite [url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache free[/url] midsole offers lightweight revolt level, outstanding durability and unbroken outsole can do to greatly lower the all-embracing avoirdupois of the shoe. Qianzhang pods on the outsole and heel-shaped Unripened rubber enhances the shoe multi-directional drag on sundry surfaces.

    Reply
  • You necessitate some tomato basil and mozzarella. In kindness of indoor depress into service, these slippers are as be exposed and manueverable as sneakers.

    Posted by Soaceddew on 04/24/2013 11:11am

    Has just released several mod color Democratic Inneva Woven shoes, Nike recently with another pathway to lure shoes with contrary styling to all [url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache free[/url] eyes. This brings special issue Unfastened Inneva Woven is a Fair-skinned Name of works in the series, represents shoes Italian made the assurance. Latest Safe from Inneva Woven jet and pornographic are readily obtainable in two color schemes, to hand-knit Woven vamp in summing-up to infiltrated Italy's [url=http://markwarren.org.uk/property-waet.cfm]air max 90 uk[/url] finest crafts, meanwhile gives athletes arrange to the foot of relieve, the most superior affair is the goal of Unstinting 5 configuration, barefoot consider it pass on give birth to cannot be ignored. Nike Sovereign Inneva Woven SP Milk-white Id Wedge on Demonstration 16 at outlets for everyone the [url=http://northernroofing.co.uk/roofins.cfm]nike free run[/url] kind on the shelves, and on sale in restricted form, interested friends should produce results fasten publicity to Nike announced the news.

    Reply
  • wholesale snapback caps

    Posted by xxds2gj on 04/01/2013 06:01am

    [url=http://snapbackhatwholesale.webs.com]snapback hats wholesale[/url] snapback hats wholesale u jloj [url=http://snapbackhatwholesale.webs.com]wholesale snapbacks[/url] wholesale snapbacks l ywkv[url=http://snapbackhatwholesale.webs.com]snapback hats wholesale[/url] snapback hats wholesale c lijs[url=http://cheapsnapbacksforsalezone.webs.com]snapback hats cheap[/url] snapback hats cheap e piii[url=http://snapbackhatwholesale.webs.com]wholesale beanies[/url] wholesale beanies k vdbc[url=http://bestbaseballcap.webs.com]hats wholesale[/url] hats wholesale k ezuk [url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks online[/url] cheap snapbacks online n ljno [url=http://cheaphatsmall.webs.com]snapbacks for cheap[/url] snapbacks for cheap m fcig[url=http://snapbackhatwholesale.webs.com]snapback hats wholesale[/url] snapback hats wholesale x egxe[url=http://cheaphatsmall.webs.com]cheap hats[/url] cheap hats q hrjf[url=http://snapbackswholesalezone.webs.com]snapbacks wholesale[/url] snapbacks wholesale u shsr[url=http://cheapsnapbackshat.webs.com]cheap hats[/url] cheap hats i klkw [url=http://cheapsnapbackshat.webs.com]cheap snapbacks online[/url] cheap snapbacks online w bmns [url=http://snapbackswholesalezone.webs.com]snapback wholesale[/url] snapback wholesale s xwer[url=http://bestbaseballcap.webs.com]hats wholesale[/url] hats wholesale l wmoq[url=http://cheaphatsmall.webs.com]cheap hats[/url] cheap hats s offr[url=http://cheapsnapbacksforsalezone.webs.com]snapback hats cheap[/url] snapback hats cheap g tvhj[url=http://wholesalefittedhat.webs.com]wholesale fitted hats[/url] wholesale fitted hats d cdpk

    Reply
  • cheap snapbacks from china

    Posted by zyexpenueMoxjef on 03/29/2013 11:15pm

    [url=http://www.cheapforsunglasses.com]oakleys cheap[/url]snapback hats wholesale [url=http://www.bestcheapsnapbacks.com]cheap snapbacks from china[/url]cheap sunglasses [url=http://www.cheapforsunglasses.com]oakleys cheap[/url]cheap sunglasses [url=http://www.bestcheapsnapbacks.com]cheap snapbacks for sale[/url]cheap oakley [url=http://www.bestcheapsnapbacks.com]cheap snapbacks[/url]cheap snapbacks free shipping

    Reply
  • wholesale oakley sunglasses

    Posted by cgliliImpumpwzc on 03/29/2013 10:12am

    http://discountsunglasseshoo.webs.com - discount ray ban sunglasses cheap http://discountoakleysunglassesho.webs.com - oakley discount discount ray ban http://akeoakleysunglasses.webs.com - fake oakleys oakley discount http://cheapsunglassesshop.webs.com - cheap sunglasses,,, cheap oakley frogskins http://wholesalesunglasseschic.webs.com - wholesale oakley sunglasses discount sunglasses

    Reply
  • cheap sunglasses,,,

    Posted by hgliliImpumpbzs on 03/29/2013 10:00am

    http://discountoakleysunglassesho.webs.com - discount oakley sunglasses fake ray ban http://sunglasssaleulow.webs.com - cheap oakleys wholesale oakley sunglasses http://bestsunglassesshop.webs.com - fake oakleys oakleys for cheap http://discountsunglassessale.webs.com - discount ray ban oakley sunglasses discount http://discountsunglasseshoo.webs.com - discount sunglasses oakley sunglasses cheap

    Reply
  • French Maid Lingerie

    Posted by Fishnettk1059 on 03/29/2013 09:44am

    http://G-string.webs.com - sexy stockingsWhen it comes to choose the right color, stick to one that compliments your look The more skin you show, the hotter it is http://SexyChemise.webs.com - Chemise LingerieAnd, in the grand scheme of things, letting our sex pot out one day of the year may very well lead to her making an appearance more regularlyBlue is a cool and calm color which also denotes stability, confident and reliability http://SexyChemise.webs.com - Lace ChemiseDressing like a mermaid is sure to seize the notice of that specific someone you been admiring lately, and make you the envy of all the other girls Petite women should opt to baby dolls with simple design while larger women can choose styles with details that will attract attention to small body parts http://cheapspicylingerie.webs.com - Cheap Bustiers?s boxers, and they have it Meanwhile, red and yellow may stimulate the desire for food http://G-string.webs.com - sexy g-stringscom This is an online dreamgirl lingerie retailer which offers free shipping for orders that are above $75

    Reply
  • Sexy Lingerie

    Posted by Fishnetqi1070 on 03/29/2013 09:27am

    http://sexylingerieshops.webs.com - Trashy LingerieThis is an online dreamgirl lingerie retailer which offers free shipping for orders that are above $75 Dressing like a mermaid is sure to seize the notice of that specific someone you been admiring lately, and make you the envy of all the other girls http://discountsexylingerie.webs.com - discount LingerieWhen looking for lingerie, try to take into account what she likes Let the environment be tasteful, yet celebratory http://SexyChemise.webs.com - womens chemiseLingerie can now be boasted by every woman regardless of her size and figure Azure lingerie is one of the internet http://babydolllingeriee.webs.com - babydoll lingerieHence, a blue bed sheet is also a unique gift Therefore, it pays well to have some fair idea about the wholesale lingerie http://sexylingeriecostumes.webs.com - Sexy UnderwearAlthough the garment had been around for decades, the name "baby doll lingerie" was first introduced when Carroll Baker appeared in one in the 1956 film "Baby Doll All these types of wholesale sexy dresses serve as a status symbol for the women and also depict their personality as a whole

    Reply
  • fake ray ban wayfarer

    Posted by egliliImpumpfvg on 03/28/2013 10:27pm

    http://onlineguciisunglass.webs.com - ray ban sunglasses cheap oakley sunglasses discount http://discountoakleysunglassesho.webs.com - discount sunglasses oakley sunglasses discount http://sunglasssaleulow.webs.com - oakley sunglasses cheap cheap sunglasses online http://sunglasswholesaleofgucci.webs.com - cheap sunglasses online discount oakley sunglasses http://qualityguccisunglass.webs.com - cheap oakleys replica oakley sunglasses

    Reply
  • http://www.oakleysunglassesoutc.com/ wcsyzm

    Posted by http://www.oakleysunglassesoutc.com/ Mandyyah on 03/28/2013 04:30pm

    ghd,At the status of plus the Li Hongzhang the Zhili Jiangchen of power and influence, a separate faction at least than the year Chunwang in old rival Tonghe patron Chunwang Once Naoqi awkward Chunwang in which half-hearted stronger Even better is Li and Weng Tong is the real life and death, great hatred. Empress Dowager Cixi hear nodded and said: Let Li Hongzhang redeem oneself, the battle is not even crushed it? The Sun Yuwen hear hearts delight, cheap ghd from this statement hear it, Empress Dowager Cixi and the idea of ​​the war, in fact ghd australia long eunuch Li Lien Ying know that kind of Empress Dowager Cixi of the Sino-Japanese war began the momentum long past, as birthday looming, the Empress Dowager Cixi has on more than one occasion to reveal the thoughts and war Taiping had life. It is even more inappropriate punishment! Northern corner of the force, stroke Woren dumping country division, Li Hongzhang has played tough enough, but according to the current situation, the war also marked a period of time, this time punishment ghd straightener,com/" title="ghd hair straightener"ghd hair straightener going to think?

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Go Deeper

  • This interactive white paper from CIO Magazine and EMC lays out the benefits of big data and predictive analytics, provides tips on how to …
  • This buyers guide provides independent research and test results to help you determine your endpoint protection requirements and identify …
  • Regardless of the size of your business, a Denial of Service attack can disrupt your organization's website and network services. Download …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds