Search code examples
c#tcp

How to continue with a script only after it was received by a TCPClient?


I thought about sending a packet with one byte to the server and to write on the serverside the following code:

int a= stream.ReadByte()
if(a==-1){
//client received data 
}

The stream is a NetworkStream
I want to do this because after this I start a timer on the server. The timer should only start if the clients have updated their values.


Solution

  • A Stream only has limited options:

    • it can return a positive number to say "yes, I have provided this much data"
    • it can return a non-positive number to say "EOF: I have no data, and never will have more data"
      • (the above also map similarly to ReadByte(), except the second point becomes "negative" for no data)
    • it can block, waiting for one of the above two conditions to be possible
    • it can throw an exception

    What it can't do is say "I currently do not have data, but I might in the future". As such, you can't use the Stream API to check whether there is data. Instead, it is typical to use an async API (usually on the Socket itself, or another abstraction that isn't Stream), to allow you to process a callback when data becomes available. There is also the .Available property on a .Socket which tells you the amount of data currently buffered and available for consumption (note: this API is typically only used to choose between sync vs async IO).