开发者

How can I send data with a TcpListener, and wait for the response?

开发者 https://www.devze.com 2022-12-09 02:13 出处:网络
I have the following code: using (TcpClient client = new TcpClient()) { client.Connect(host, port); using (SslStream stream = new SslStream(client.GetStream(), true))

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 a server, and then wait for the response.

Is this the proper way to do it?

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


The overall structure of your code looks right.

byteRead = stream.Read(buffer, 0, 1000); will block until all of the response data is retrieved from the server. If the remote server shuts down the connection (timeout, etc), 0 will be returned.

See the remarks found here.

The framework will properly deal with packets lost during network operations - don't worry about them.


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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消