C# TELNET Client
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); 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 iscalled once the connection is complete, it displays connection error ifit fails or it sets up the OnRecievedData callback if connection issuccessful. public void ConnectCallback( IAsyncResult ar ) To begin to get you data asynchronously fromthe socket , it is necessary to setup an Asynchronous Callback tohandle events triggered by the Socket. For eg : New data at the socketport or oss of connection. This is done using the following method; public void OnRecievedData( IAsyncResult ar ) Download Executable
// 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 ) ;
{
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!" );
}
}
{
// 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 SourceMost Commented Articles :




02. Jul, 2006 by 







No comments yet... Be the first to leave a reply!