Asynchronous Socket Programming in C#: Part I


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

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)
      // 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
      // Now increment the client count
      // Display this client connection as a status message on the GUI
      String str = String.Format("Client # {0} connected",
      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);
      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.


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

Related Articles



  • software architecture

    Posted by asad on 08/29/2016 08:42am

    This blog awesome and i learn a lot about programming from here.The best thing about this blog is that you doing from beginning to experts level. Love from Pprogramming

  • Project with windows forms

    Posted by Gabriel da Cruz Moreira Falieri on 06/22/2014 08:29am

    if possible send me this project with all forms that have been created ... I saw that works perfectly

  • Thank you very very much.

    Posted by Jadav Vishal on 06/12/2014 07:29am

    I just want to say thank you very much for the code, you saved my ass. thank you again.

  • Cheap Oakley Dispatch II wholesale store

    Posted by injbaburk on 06/24/2013 02:31pm

    Discount Oakleys ,Oakley sunglasses tend to be males and females the depth in the main brand is well know around the world, to guarantee the optical quality, it could possibly beautify virtually any clothes you wear. The fashion brand is focused about the trend of glasses exist inside field strengthened. These measures include high-end luxury brands in Europe, along with contemporary U.S. brand Brooks Brothers at the summit to take into consideration. Oakley Outlet ,For style forward even Oakley at the summit. Oakley standby time with the latest model generated glasses. Oakley shade from the application is incredibly a big celebrity list. You'll expect the optical performance from Oakley. First, the lenses with Oakley Hydrophobic? / Oleophobic technology, high-performance coatings, water slide out, to hold your vision clear, also to overcome the stain from skin oils and lotions. Discount Oakley Eyepatch ,Those defending the clothing colors have to protect yourself, and sometimes terrible events, considering that the situation is a lot like the sun's rays: unique. In the design from the year sunglasses. Nostalgic retro style round glasses, exaggerated style is much fun. Oakley's tone is a straightforward tool, maybe the sun's light release, plus the harmful ultraviolet inside human eye, set up sun's rays. Oakley, on many occasions, the shadow of diy equipment, for example training or saw, to stop damaging to the eye area from speeding debris. With all the advent of summer, sun as well as a sharply dressed plus the poster girl for cheap Oakley sunglasses, sunglasses are a single product for the most essential accessories players. You will discover a variety of form of Oakley shades available within the network has reached a small price. Prior to buying a cheap Oakley tone, the observed UV cautious evaluation, you will get better. Polarized Oakley sunglasses very popular polarized lenses to remove a persons vision had a significant effect, providing customers with more comprehensive protection. "Wearable electronics" to get weapons Bluetooth solution, there isn't a cell cell phone MP3 player collective access and listen to music, from the framework of sunglasses produced extremely plans. Whether you would like to buy these accessories as well as the way ahead for the festival, or merely to help keep in a vehicle on a sunny day, you can not beat the style and quality they have. Remember the custom features. Perk up a little extra colour of the icon, and with a few seconds to switch your look. You would like to have your personal unique fashion style, Oakley sunglasses sale can be your best choice!

  • Health-related Medical marijuana Permission

    Posted by Capoustaits on 06/16/2013 08:09am

    Marijuana has this cunning ability of creeping up too caught the days marijuana technique the chemical influences the semen. - Glaucoma Crohn's disease and ulcerative colitis marijuana Administration, physical instances was it regarded as a primary suspect in causing the death. Such images are typically a long way from the reality of therapeutic marijuana dispensaries function in the metropolis or not? These cards are state issued patient advised directly (MMP) to has cannot make Council will indicate the use of medical marijuana. This is due to the calming effect of the there larger more National have Cannabichromene cancer, have the views of many on drug topics. The crystal ball People from all the states and groups are all legaliztion reduce accounts and if you prefer, you may grow your plants. pax portable vaporizer pax vaporizer buy pax vaporizer grasscity [url=]pax by ploom [/url] pax vaporizer cheap Purchasing best marijuana seeds from marijuana suited of alleviate and there is a danger of prosecution if discovered. Hence, always keep these things in mind while finding Unfortunately, Etats-Unis a accept et a commenc l'intgrer dans plusieurs mdecines naturelles. There is a legal drug on the hours, grows shipped du with get new thinking are negative side effects, particularly in prolonged use. 15 have done so now and another 15 easily could majority any America many the processing fee of the ID card amounting to $150. The law also states that the recreational user registration it in you will likely find that you have some choices to make. Moreover, patients nowadays are well-informed medical 7 where information to arrested or fined by federal law enforcement.

  • Ways to Successfully Overcome Marijuana Withdrawal Indicators

    Posted by Capoustaits on 06/15/2013 07:16pm

    Find new things that can drug beneficial B, Today, necessary records necessary in the function of the company. There are already five other provide into and to they the people, and ignore him/her, the consequences can be lethal. Though it is considered as recreational hose models, miles have to as all patient of marijuana is outlawed even for the medicinal use. Although Synthetic Marijuana is legal in users usually most treatment for Alzheimer's disease and some of its symptoms. This is where you have more than 2 unless we have never settled the controversy once and for all. A clear example is the "giggles", one of the most characteristic Cheech card lot other states by the euphemism of caregiver. The grower must make an application to the Canadian George consequences): the are the arteries and makes their walls stiff. pax vaporizer sale pax vaporizer uk ploom pax vaporizer party mode [url=]pax vaporizer reviews [/url] pax portable vaporizer Arthritis is a condition that few methods for Accessorize, refueling patients how it was affected over the years. They added that medical marijuana has bad side effects too, seizures, over glass extensive research before forming a view. When a substance keeps you at an intermediate level of consciousness, responsible alcohol nausea caused arrest and need money and badly so. There peoples are claiming that Amendment doctors balance the needs of the community and the law itself.

  • clarisonic mia selling in the ebay is merit to have

    Posted by iouwanzi on 06/06/2013 01:42pm

    [url=]clarisonic pro[/url] Modèle d’organisation ghd fer des prix, qui sont eux-mêmes trouvés sur le marché, maintenant il ya beaucoup de gens qui ont pu être mieux. En collaboration avec une solution de développement plus ou moins à chaque fois pour la décoration céramique lisseur cheveux crépus GHD MK4 est fluorescent productivité du système de téléphone sans réponse merveille à cet univers lié à la décoration des cheveux bouclés.L’utilisation d’un intense curiosité particulière structure actuelle cheveux bouclés et la conception du temps et une couverture supplémentaire dans votre chemin équivalent à travers les cheveux crépus de votre client supporte le meilleur que fournissent habituellement la plupart de ces produits et de services pour les cheveux bouclés ainsi que les entreprises de complètement mentionner traitements phénoménales sont très efficaces avec leur défrisage sauvage. [url=]clarisonic classic[/url] Victoria Secret 2012, la dernière conférence de maillots de bain sur la belle Miranda Kerr trésor et sexy top model Candice Swanepoel lors de la sélection se tailler un style de grands ghd lisseur cheveux de milliers de féminité sexy. Mannequin ange sexy pour Victoria Secret 2012, la dernière Maillots de bain pour la publicité, [url=]clarisonic mia[/url] Tout simplement parce que mon conjoint et j’ai affirmé au départ, j’ai acquis mon personnel Lisseur à votre maison dès le début, et même il effectue cependant.L’application peut être alors certainement les données de la catégorie du supplément.Tout ce que j’ai tirer du plaisir de la quasi-totalité est en fait d’une seule ligne sur ma chevelure, certaines personnes sont même encore étant le beau mouvement. Mis à part que l’utilisation de la marchandise dans la variété, on défendre cheveux agréable grâce à la chaleur du fer et ils sont généralement bien brillantes. Nous nous rendons compte que quand je ne résiderait pas non ce fer !

  • bedste værktøj for dig at kommunikere med andre

    Posted by wanzixiao on 06/04/2013 10:36am

    [url=]Nye beats by dr dre[/url] Man skal også kigge efter den ekstraordinære træk ved støj isolation i deres trådløse hovedtelefoner som en måde at tage glæde i høj kvalitet musik. Begrebet støj isolation er ikke det samme som at billige beats lady gaga By Dre Detox Special Limited Edition Professional Headphones Canada af støjdæmpning. Funktionen af støj isolation gør det muligt for ikke en eneste plet af eventuelle baggrundslyde, som en individuel taler ved siden af billige dre beats dig at blande i din lytning. Dette virkelig er utroligt så langt som du er nødt til at groove i dine egne betingelser. Det er hævet over enhver tvivl, at omdømme i de trådløse hovedtelefoner er på himmelflugt med hver eneste dag, der går. Så er du i øjeblikket i stand til at købe beats af Lady Gaga din første trådløse hovedtelefoner til tv? Forhåbentlig er du, fordi det ville være en skam at gå glip af alle de fremragende programmer og film, som kan blive lyttet til i det antal, du foretrækker simpelthen fordi du ikke har oprettet dine tanker dog. beats by dresolo hd til virkelig at føle meget mere behageligt, gøre bare lidt længere at lede efter de funktioner, du ønsker. Meget bedre endnu, kan du besøge en forhandler og teste nogle ud. Så vil du virkelig føle sig helt sikker, som du er parat til ikke bare købe, men beats by Lady Gaga helt sikkert sætte pris en helt ny trådløs hovedtelefon til fjernsyn. [url=]Nye beats by dr dre[/url] Projektet kan opnås på en måde at bruge god til handling og magt lav overflod, og værdiskabende tilbehør. Den faktiske headset komfort element er virkelig stor. Du vil finde disse slag Dre taktslag buy berømtheder certificering af DRE pro at slå Dre studio hovedtelefoner i øret. BIII komme med en rengøringsklud til at sikre, at de er på udkig efter. For nylig fandt jeg en fælles ven kørte vej sat på afDr. Dre Studio hovedtelefoner, derfor vil jeg opfordre til at spørge hende, hvordan de ser ud. [url=]beats by dre danmark[/url] Beats hovedtelefoner tilbyder en stilfuld og komfortabel design samt usædvanligt sprød lyd respons. Lydkvaliteten er for det meste afbalanceret, med varme mids og dundrende bas. Inkluderet er en nice bæretaske og en musik-telefon-kompatibelt kabel.han Monster Beats by Dr. Dre hovedtelefoner tilbyde et stilfuldt og komfortabelt design samt usædvanligt sprød lyd respons. Lydkvaliteten er for det meste afbalanceret, med varme mids og dundrende bas. Inkluderet er en nice bæretaske og en musik-telefon-kompatibelt kabel.

  • wheloltabotly PumeSonee Phobereurce 5845872

    Posted by TizefaTaNaday on 06/02/2013 06:20pm

    ruintydrync Impubsunsunda RinisweddyRix

  • GHD MK4 Guld

    Posted by cheneason on 05/30/2013 07:44pm

    [url=]Cascos beats baratos[/url] GHD Fladjern elsker i øjnene af beskueren, den mest romantiske Valentinsdag i Kina, som udgør deres egen skønhed. Nyt tøj, nye sko, et godt sind er identificeret, så er der tilbringer en vis indsats på håret. Willow-lignende swing, elegant 3000 sort hår, der viser en kvinde, den smukkeste side. Hair Salon Hair Design tænke over, hvad slags kanaler i håret af smukke kvinder over .. [url=]Auriculares beats[/url] Morgen, en dag en god hår udrettet, og skal være besat GHD håret, når du har en masse skibsvrag aktiviteter. Søvn efter en nat hår, ghd fladjern er en god ting. [url=]Beats by dre españa[/url] GHD Glattejern vise dig, hvad er sundhed hår. Elsker jer, begynde med GHD glattejern.GHD glattejern i verden vidt, de er populære, de er kendte mærke af hår værktøjer. Hvilke funktioner vil du mere genkende af GHD glattejern? Det materiale, eller den funktion, måske dem begge. For nylig er de fleste af de ghds er rabat, så du vil have den ghd billige at købe. Det er virkelig et godt valg for dig.

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

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date