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 MethodsAsynchronous Methods
     
     
  1. Connect()
     
     
  1. BeginConnect()
  2. EndConnect()
     
     
  1. Receive()
     
     
  1. BeginReceive()
  2. 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:

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

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.

 
 
  1. public void OnClientConnect(IAsyncResult asyn)
  2. {
  3. try
  4. {
  5. // Here we complete/end the BeginAccept() asynchronous call
  6. // by calling EndAccept() - which returns the reference to
  7. // a new Socket object
  8. m_workerSocket[m_clientCount] = m_mainSocket.EndAccept (asyn);
  9. // Let the worker Socket do the further processing for the
  10. // just connected client
  11. WaitForData(m_workerSocket[m_clientCount]);
  12. // Now increment the client count
  13. ++m_clientCount;
  14. // Display this client connection as a status message on the GUI
  15. String str = String.Format("Client # {0} connected",
  16. m_clientCount);
  17. textBoxMsg.Text = str;
  18.  
  19. // Since the main Socket is now free, it can go back and wait
  20. // for other clients who are attempting to connect
  21. m_mainSocket.BeginAccept(new AsyncCallback
  22. ( OnClientConnect ),null);
  23. }
  24. catch(ObjectDisposedException)
  25. {
  26. System.Diagnostics.Debugger.Log(0,"1","\n OnClientConnection:
  27. Socket has been closed\n");
  28. }
  29. catch(SocketException se)
  30. {
  31. MessageBox.Show ( se.Message );
  32. }
  33.  
  34. }

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.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值