Monday, December 26, 2011

Bytes vs String Over Network


Bytes vs String Over Network

Message in bytes format is always good to transfer data over network compare to string.
Communication of message in bytes format required convertion of every data while sending and receving at both end of connection.
In scenario of Stock Market or Very fast data transfer over network, It is recommened not to use bytes format to send and receive data over network because it consume more time for conversion of data compare to volume of data, Hence in this case string format is recommeneded for data comunication

Asynchronous TCP Client Easy Example


 private TcpClient tcpClient = null;

         public void ConnectToServer()
         {
                try
               {
                tcpClient = new TcpClient(AddressFamily.InterNetwork);

                IPAddress[] remoteHost = Dns.GetHostAddresses("hostaddress");
              
                //Start the async connect operation          

                tcpClient.BeginConnect(remoteHost, portno, new
                              AsyncCallback(ConnectCallback), tcpClient);

                }
                catch (Exception ex)
                {
Logger.WriteLog(LogLevel.Error,"ex.Message);
                 }
         }
      

        private void ConnectCallback(IAsyncResult result)
        {                      
            try
            {
              //We are connected successfully.

               NetworkStream networkStream = tcpClient.GetStream();

               byte[] buffer = new byte[tcpClient.ReceiveBufferSize];

              //Now we are connected start asyn read operation.

               networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);
             }
             Catch(Exception ex)
             {
Logger.WriteLog(LogLevel.Error,"ex.Message);
              }
          }
      

          
          /// Callback for Read operation
         private void ReadCallback(IAsyncResult result)
         {    
  
            NetworkStream networkStream;

            try
            {

                networkStream = tcpClient.GetStream();  
        
            }

            catch
            {
Logger.WriteLog(LogLevel.Warning,"ex.Message);
             return;

            }        

            byte[] buffer = result.AsyncState as byte[];

            string data = ASCIIEncoding.ASCII.GetString(buffer, 0, buffer.Length );

            //Do something with the data object here.

            //Then start reading from the network again.

            networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);

        }