C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » .NET Framework »

Asynchronous socket Programming using C#


Posted Date: 06 Jul 2004    Resource Type: Articles    Category: .NET Framework
Author: Swanand UmaranikarMember Level: Bronze    
Rating: 1 out of 5Points: 7



Introduction

This is a attempt to answer few of the questions regarding Asynchronous socket programming using C#. I have been working in the socket programming domain using C/C++. This will be an attempt to do the similar thing using C#.

This article speaks about the creation of TCP/IP socket and use of this connection between applications. The Client-Server architecture can be local or distributed over the network. We will discuss a different aspect of a client-server architecture, which uses some thing different than a conventional threads.

A Client-Server architecture

The architecture used here is simple, it has a server that listens for clients to connect.
There is sequence in which the client can connect to the running server. Server should be "Listening" before a connection is made to client.

Though the .NET concept of sockets is used for many applications like WebServices and Remoting, the major advantage is that the low level socket is done for programmer. Hence no need to use direct sockets. This is not true though, while interfacing to other non .NET systems sockets.

The server listens for clients to connect. When a connection is made, the server will accept the connection and return a acknowledgement. There should be some way to detect the loss of a connection in system. This can be a "Polling type acrchitecture" or a "event based architecture"

1. Using Polling

System.Net.Sockets provides provides a class TcpListener. This class has a method to listen for client connections and process them.

The following code shows the use of the TcpListener class :


private Socket Myclient = null;

//Create a listener
TcpListener listener = new TcpListener( PortNumber );

//Start listener
listener.Start();

//Listen in a loop
while(true)
{
byte [] MyBuff = new byte[127];
if( listener.Pending() )
{
//Accept the connection
Myclient = listener.AcceptSocket();

//Send acknowledgment.
Myclient.Send(/* data to be send*/);
}
else
{
//Wait for the request
Thread.Sleep( 100 );
}
}


2. Using socket events

The event based method is more suitable than the polling method in the applications like Chat servers.

First identify the name and address of the server:

//Get the local m/c name and address
IPAddress [] aryAddr = null;
string HostName = Dns.GetHostName();
IPHostEntry ipEntry = Dns.GetHostByName( HostName );
aryAddr = ipEntry.AddressList;



Using the address id bind the listener to the same address. The following shows this binding and listing. Also add an event handler which is pointing to all connection requests.
This will reduce the overhead of polling.


//You can use "C:\WinNT\System32\drivers\etc\Services" to find out the port numbers.
int nPort = /*any port which is available*/;

// Create the listener socket
Socket listener = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
listener.Bind( new IPEndPoint( aryLocalAddr[0], nPort ) );
listener.Listen( 10 );

// Setup a callback routine for connection notification.
listener.BeginAccept( new AsyncCallback( /*method name*/), listener );



Now write a routine which will be active, when connection is requested by client.
(This is the method which will be passed in the above code line instead of /*method name*/)


Socket Myclient;
public void OnConnect( IAsyncResult ar )
{
Socket listener = (Socket)ar.AsyncState;
Myclient = listener.EndAccept( ar );

Myclient.Send(/* data to be send*/ );
listener.BeginAccept( new AsyncCallback( OnConnect ), listener );
}


The client side code is fairly simple,
What we have to do is:
1. Create a socket
2. Connect a socket
3. Call BeginReceive
4. Fire Connection Accepted event.
5. Send the data
6. Close the socket :)

Summary

Though it is simple to use Sockets it requires a good amount of coding.
The above article is just a over view of the concepts that can be used while having your own Cleint-Srerver application. (While writing this article, have taken help from various sources, and mainly MSDN.)




Responses

Author: Satish Ramahnujan    19 Aug 2004Member Level: Bronze   Points : 0
Was helpful and good. As the article mentions, there is a quite a bit of coding there. As it is in C# found it difficult to use it in VB.net.


Author: James    08 Dec 2008Member Level: Bronze   Points : 1
Very nice article. Exactly what one needs for implementing a listener socket in C# if they haven't done it in that language before, except... might want to update it to include the namespaces.


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Clear the Forms control which either in a Group box or any container control
Previous Resource: One small Tip about Using Keyword as properties or functions......
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
Related Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use