Looking at examples online, all of them seem to have:

int read = s.EndReceive(ar);

	if (read > 0) {//Some code}

The question I have is...why?

Why bother with the if (read > 0) when the MSDN says that EndReceive blocks until data is received?

If you call int read = s.EndReceive(ar); your code execution halts until the socket receives something. Once it does, it stops blocking and then will evaluate the if statement...wouldn't the if statement always return true or is it possible to receive 0 bytes?

Recommended Answers

All 6 Replies

It's possible to receive 0 bytes. The sender can send as much or as little data as they want.

So it's possible to send bits?

I'm lost. Even if it was possible to send like 2 or 3 bits which is less than 1 byte, how would it even evaluate the if statement considering that 0 is an integer, and so is "read" in this example...I would think an exception would be thrown or a potentially incorrect value used if you tried to assign a decimal value to an integer?

How would you send 0 bytes? If EndReceive blocks until it receives data, it must be receiving something for it to unblock right?

You can't really send bits as they are part of a byte, but you could send a byte in which only 1 bit has meaning.

You'd send 0 bytes by sending an empty data packet. At a level below where you are working at the system creates a packet. This packet has information about who is sending it, some status info and the actual data being sent. It's possible to just create an empty packet with no data.

I believe you can do this in C# too. Just create a zero length byte array and send it from your client.

So the packet really isn't "empty" perse, the sender's system sends packet data but the actual "data" is empty.

Is there someplace I can read about what is actually sent in addition to the data? You indicated status info etc...what exactly is added? Is there a way for an application in C# to actually extract and use that data that the system adds?

TCP. I don't believe C# (without using P/Invoke) will give you that low a level of access.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.