开发者

Timeout in Socket.Recieve

I filched the following code from net to get GMT time from the site time-a.nist.gov. This code runs great but once in a blue moon it hangs. When I pause debugging the green arrow with the message "This is the next statement to execute when the thread returns from the current location" shows next to s.Receive(ntpData);

        public static DateTime GetNetworkTime(IPEndPoint ep)
        {
            Socket s = new Socket(AddressFamily.InterNetwork, 
                                  SocketType.Dgram, ProtocolType.Udp);

            s.Connect(ep);

            byte[] ntpData = new byte[48]; // RFC 2030
            ntpData[0] = 0x1B;
            for (int i = 1; i < 48; i++)
                ntpData[i] = 0;

            s.Send(ntpData);  
            s.Receive(ntpData);
            .
            .
       }

So I added the lines

 s.SendTimeout = 1000;
 s.ReceiveTimeout = 1000;

Now it doesnt hang but throws the exception "A connection attempt failed because the connected party did not respond properly after a period of time"

StackTrace: at System.Net.Socket.Recieve(Byte[] buffer, Int32 offset,Int32, SocketFlags socketFlags)

Is this a server site (time-a.nist.gov) issue and hence no recourse except to call it again?

Also is there any way to handle this exception and call the GetNetworkTime method again.

I'd appreciate any help on开发者_StackOverflow中文版 this problem. Thanks in advance


The Socket Timeouts only work when you are using the async versions of the Read and Write methods: BeginRead and BeginWrite. The synchronous versions will hang indefinitely or until the connection is terminated.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜