How to test for a broken connection of TCPClient after being connected?

前端 未结 6 1569
-上瘾入骨i
-上瘾入骨i 2020-12-14 03:08

I\'ve been fighting with one problem for a whole 3 days I can\'t find any solution, please help :)
I work with Visual Studio 2010 and C# language.

I have a devic

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-14 03:52

    Just in case anyone else needs something simple and effective.

    This is the code I came up with

                while (true)
                {
    
                    string s = null;
                    DateTime readLag = DateTime.Now;
                    try
                    {
                        s = streamIn.ReadLine();
                    }
                    catch (Exception ex)
                    {
                        SocketException sockEx = ex.InnerException as SocketException;
                        if (sockEx != null)
                        {
                            OnDebug("(" + sockEx.NativeErrorCode + ") Exception = " + ex);
                        }
                        else
                        {
                            OnDebug("Not SockEx :" + ex);
                        }
                    }
    
    
    
                    if (enableLog) OnDebug(s);
                    if (s == null || s == "")
                    {
                        if (readLag.AddSeconds(.9) > DateTime.Now)
                        {
                            break;
                        }
                    }
                    else
                    {
                        CommandParser(s);
                    }
                }
    

    What I got was native error 10035 every time a read failed but would block.

    When the connection was trashed, I instantly got a return with no data.

    Setting the readLag.AddSeconds() to just below my read timeout would give me a pretty good idea that the time never elapsed, and I got no data. Which should not happen.

    Soon as this criteria popped up, I just kick out of the loop and the thread ends.

    Hope this helps anyone else out there.

提交回复
热议问题