开发者

Socket closing automatically

Is there a reason why a Socket should close by itself, after 2h? I am receiving data every second from this socket, and writing back some tiny "keep-alive" data every 30s.

Before sending, I check if socket开发者_StackOverflow中文版 is still connected using the following method:

public bool IsSocketReadyForWriting(Socket s)
{
   try
   {
      if (!s.Connected)
      {
          Log.Info("Socket.Connected was false");
          return false;
      }

      // following line will throw if socket disconnected
      bool poll = s.Poll(2000, SelectMode.SelectWrite);
      if (!poll)
      {
         try
         {
            // if poll is false, socket is closed
            Log.Info("poll is false");
            this.Close();
         }
         catch { }
         return false;
      }
      Log.Debug("still connected");
      return true;
   }
   catch (Exception ex)
   {
      Log.Error("Error while checking if socket connected", ex);
      return false;
   }
}

Everything works fine for about 2h, then suddenly Socket.Poll returns false, and the Socket gets closed.

Is there a setting which controls this, or am I doing something really wrong?

[Edit]

Forgot to mention: I control both server and client side of the link. These are both C# apps, one of them creates a listening socket, the other one opens a connection and sends data. They communicate without problems for 2h (no memory leaks and stuff), then the socket closes.

When this happens, I can reconnect the socket again easily, but I am just wandering if anyone knows why could be the reason for this.


By default a TCP socket is writable when there's at least one byte of space available in the socket send buffer. To reverse that - the socket is not writable when there's enough unacknowledged data sitting in the "output queue".

That said, pull out wireshark or whatever Microsoft provides for packet sniffing and see what's going on on the wire. Are your heartbeat chunks getting ACK-ed? Does the receiver window stay open or does it go to zero? Or are you just getting explicit RST or a FIN from some intermediate switch?

One way to mitigate temporary clogged pipe is to increase the send buffer size, which is kind of tiny by default on Windows - 8192 iirc. See the setsockopt (.NET probably has a version of that) and the SO_SNDBUF option.


Could be the server that is closing the connection? Do you have control over it?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜