套接字的状态从“已连接”更改为“已断开连接”

时间:2012-07-03 20:36:55

标签: c# sockets asyncsocket

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

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

下面是我的连接代码,我有一个循环不断检查套接字状态本身,如果我检测到状态是"断开连接" 我称之为再次连接()功能。每次我调用Connect()时,我都注意到我的套接字状态再次回到已连接

所以我的问题是:

 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 });
        }
    }

0 个答案:

没有答案