0

我有两个应用程序,一个通过 TCP Socket 连接到另一个。我遇到了一个问题,经过长时间的故障排除后,我开始认为根本原因是由于 Socket 断开连接,也就是 Socket.state 更改为Disconnected

我得出上述结论的原因纯粹是阅读代码并分析它们。我需要证明是这种情况,因此我的问题是你有没有遇到过这种类型的问题,即即使在尝试连接到它们之后,套接字实际上仍然断开连接?

下面是我的连接代码,我有一个循环不断检查套接字的状态本身,如果我检测到状态是“断开连接”,我会再次调用这个 Connect() 函数。每次我调用 Connect() 时,我都注意到我的套接字状态又回到了Connected状态。

所以我的问题是:

 1.  Have you seen this behavior yourself before?
 2.  Do you see any problem in me calling multiple Connect() again and again?
 3.  Is there a way to simulate this type of socket disconnections?  I tried but I can't set the Socket.Connected flag.


public override void Connect()
    {
        try
        {
            sState = Defs.STATE_CONNECTING;

            // send message to UI
            string sMsg = "<Msg SocketStatus=\"" + sState + "\" />";
            HandleMessage(sMsg);

            // Create the socket object
            sSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            string sIP = "";

            // Define the Server address and port
            if (Validate.IsIPAddress(sServer.ToString()))
            {
                sIP = sServer.ToString();
            }
            else
            {
                IPHostEntry iphost = Dns.GetHostEntry(sServer.ToString());
                sIP = iphost.AddressList[0].ToString();
            }

            IPEndPoint epServer = new IPEndPoint(IPAddress.Parse(sIP), 1234);

            // Connect to Server non-Blocking method
            sSock.Blocking = false;
            AsyncCallback onconnect = new AsyncCallback(OnConnect);
            sSock.BeginConnect(epServer, onconnect, sSock);
        }
        catch (Exception ex)
        {
            LogException(new Object[] { ex });
        }
    }
4

0 回答 0