title: Error Handling in TcpClient Socket
body: <p>I am new to Sockets this is my Code to send and receive data from a server.</p>
  
  <p>This Code Works fine as long as the Client is able to receive data from the server.</p>
  
  <p>In Case the Server does not sends the answer back in the given time then the application needs to send "No Answer Received".</p>
  
  <p>How can i know if the recvBuffer is empty or NULL.</p>
  
  <p>Currently the if Condition for the recvBuffer does not work and the application tries to send empty buffer which results in  "System.IndexOutOfRangeException error".</p>
  
  <pre><code> class GetSocket
   {     
      public string SocketSendReceive(string server, int port, string cmd)
      {
          byte[] recvBuffer = new byte[1024];
          TcpClient tcpClient = new TcpClient();
          tcpClient.Client.ReceiveTimeout = 200;
  
           try
              {
                  tcpClient.Connect(server, 6100);
  
              }
              catch (SocketException e)
              {
  
                  MessageBox.Show(e.Message);
  
              }
  
              if (tcpClient != null &amp;&amp; tcpClient.Connected)
              {
                  try
                  {
                      tcpClient.Client.Send(Encoding.UTF8.GetBytes(cmd));
                      tcpClient.Client.Receive(recvBuffer);
  
                  }
  
                  catch (SocketException e)
                  {
                      MessageBox.Show(e.ErrorCode.ToString());
                  }
  
                  tcpClient.GetStream().Close();
                  tcpClient.Client.Close();
                  tcpClient.Client.Dispose();
                  tcpClient = null;
                  string tmp = Encoding.ASCII.GetString(recvBuffer, 0, recvBuffer.Length);
  
                  if (recvBuffer != null &amp;&amp; recvBuffer.Length &gt; 0)
                  {
                      string[] words = tmp.Split(null);
                      return words[1];
                  }
                  else
                  {
                      return ("No Answer Received");
                  }
              }
          return null;
      }
  
  }
  </code></pre>