Suraj
Suraj

Reputation: 36547

TcpClient - how to determine when bytes are delivered?

When using TcpClient, how do I know what the server has or has not received? For example, let's say my message is a very long string:

string myAppMessage = "was up too late coding, bla, bla, bla, ....."
byte[] allBytes = Encoding.ASCII.GetBytes( myAppMessage );

And I want to hand-off the string, in entirety, to TCP and I want to know that that entire string was delivered to and received by the server.

There seem to be some common ways to send data via TCP:

var client = new TcpClient( IP_ADDR , PORT )
client.GetStream().Write( allBytes )

-or-

client.Client.Send( allBytes )

Does either or both guarantee the delivery of the entire message? In the first case, is it only guaranteed after I call Flush() on the stream? I think one or both of the above are blocking calls. If completed without an Exception being thrown, can I take that to mean that the entire message was delivered/received?

Upvotes: 1

Views: 87

Answers (1)

usr
usr

Reputation: 171178

You need to receive acknowledgement from the other side. Alternatives:

  1. Have the remote party send you an acknowledgement.
  2. Have the remote party Shutdown(Read) the connection. Call Read until it returns 0. 0 signals that the remote side has shut down and all data was received.
  3. Call Shutdown(Write). This waits for an acknowledgement from the remote side.

Sending alone does not guarantee delivery.

Upvotes: 1

Related Questions