Search Forum
(53671 Postings)
Search Site/Articles

Archived Articles
712 Articles

C# Books
C# Consultants
What Is C#?
Download Compiler
Code Archive
Archived Articles
Advertise
Contribute
C# Jobs
Beginners Tutorial
C# Contractors
C# Consulting
Links
C# Manual
Contact Us
Legal

GoDiagram for .NET from Northwoods Software www.nwoods.com


 
Printable Version

C# TELNET Client
By Shripad Kulkarni

The telnet application makes use of Callback Function to recieve data from a socket in asyncronous mode.

s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Create New EndPoint
iep	= new IPEndPoint(addr[0],port);
// This is a non blocking IO
s.Blocking = false ;
// Assign Callback function to read from Asyncronous Socket
callbackProc	= new AsyncCallback(ConnectCallback);
// Begin Asyncronous Connection
s.BeginConnect(iep , callbackProc, s ) ;	
BeginConnect is used to commence a non blocking connection attempt. Note, even if a non-blocking connection is attempted, the connection will block until the machine name is resolved into an IP address, for this reason it is better to use the IP address than the machine name if possible to avoid blocking

The ConnectCallback function is called once the connection is complete, it displays connection error if it fails or it sets up the OnRecievedData callback if connection is successful.

public void ConnectCallback( IAsyncResult ar ) 
{
 try 
 {
  // Get The connection socket from the callback
  Socket sock1 = (Socket)ar.AsyncState;
  if ( sock1.Connected ) {
   // Define a new Callback to read the data
   AsyncCallback recieveData = new AsyncCallback( OnRecievedData );
   // Begin reading data asyncronously
   sock1.BeginReceive( m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData , sock1 );
  }
 }
 catch( Exception ex ) 
 {
  MessageBox.Show( this, ex.Message, "Setup Recieve callbackProc failed!" );
 }
}
To begin to get you data asynchronously from the socket , it is necessary to setup an Asynchronous Callback to handle events triggered by the Socket. For eg : New data at the socket port or oss of connection. This is done using the following method;
public void OnRecievedData( IAsyncResult ar )
{
 // Get The connection socket from the callback
 Socket sock = (Socket)ar.AsyncState;
 // Get The data , if any
 int nBytesRec = sock.EndReceive( ar );
 if( nBytesRec > 0 )
 {
  string sRecieved = Encoding.ASCII.GetString( m_byBuff, 0, nBytesRec );
  ............
  ............
  ...........s.
Download Executable
Download Source