How can I send data using TcpListener and wait for a response?

I have the following code:

using (TcpClient client = new TcpClient())
{
   client.Connect(host, port);

   using (SslStream stream = new SslStream(client.GetStream(), true))
   {
      stream.AuthenticateAsClient(host);

      stream.Write(System.Text.Encoding.ASCII.GetBytes(dataToSend));

      int byteRead = 0;
      byte[] buffer = new byte[1000];

      do
      {
         byteRead = stream.Read(buffer, 0, 1000);
         reponse += System.Text.Encoding.ASCII.GetString(buffer, 0, byteRead);
      }
      while (byteRead > 0);
   }
}

I send a string to the server and then wait for a response.

Is this the right way to do this?

If the server needs some time to process what I sent, will it work or will stream.Read return 0 and exit the loop? Or, if some packets from the response are lost and must be resent, will it work?

+5
source share
2 answers

The general structure of your code looks right.

byteRead = stream.Read(buffer, 0, 1000);will be blocked until all response data is received from the server. If the remote server disconnects the connection (timeout, etc.), 0 will be returned.

. .

, - .

+5
public string Method()
{
  m_Client = new TcpClient();
  m_Client.Connect(m_Server, m_Port);
  m_Stream = m_Client.GetStream();
  m_Writer = new StreamWriter(m_Stream);
  m_Reader = new StreamReader(m_Stream);
  m_Writer.WriteLine(request);
  m_Writer.Flush();

  return m_Reader.ReadToEnd();
}
-1

All Articles