Reputation: 1278
I have the following code to read the time from time.nist.gov:
TcpClient client = new TcpClient();
var result = client.BeginConnect("129.6.15.28", 13, null, null);
var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));
if (!success || !client.Connected)
// Timeout
else{
streamReader = new StreamReader(client.GetStream());
var response = streamReader.ReadToEnd();
//code
}
The problem is that sometimes ReadToEnd get frozen indefinitely, I assume because it does not reach and end.
Is it possible to set a timeout for this operation?
Or maybe a better option to read the server response?
Thanks.
Upvotes: 2
Views: 1578
Reputation: 24061
According to MSDN:
ReadToEnd assumes that the stream knows when it has reached an end. For interactive protocols in which the server sends data only when you ask for it and does not close the connection, ReadToEnd might block indefinitely because it does not reach an end, and should be avoided.
Do you know how much you're reading? If so, you can use Read().
EDIT:
I tested this code (well, something very similar) and found that ReadToEnd
works fine, unless port 13 is blocked, in which case it also runs without returning for me as well. So, check your firewall before doing this.
Better is Hans's suggestion of using an existing, well-tested NTP lib.
Upvotes: 3