BrandonPotter / SimpleTCP

Straightforward .NET library to handle the repetitive tasks of spinning up and working with TCP sockets (client and server).
Apache License 2.0
363 stars 108 forks source link

can't check if connection to server is still establshed #38

Open RedCali opened 6 years ago

RedCali commented 6 years ago

may it would be got to have an option to check whether the connection is establish or not

can use - TcpClient.Connected for that and return that via a separate getter

example which fit to my needs:

public bool Connected { get { return (_client != null) ? _client.Connected: false; } }

avcengineer commented 6 years ago

I added the following code into the SimpleTcpClient and recompiled the dll and it seems to be working to provide that function. Maybe they will add it in in the future.

       public bool IsConnected
        {
            get
            {
                try
                {
                    if (_client != null && _client.Client != null && _client.Client.Connected)
                    {
                        // Detect if client disconnected
                        if (_client.Client.Poll(0, SelectMode.SelectRead))
                        {
                            byte[] buff = new byte[1];
                            if (_client.Client.Receive(buff, SocketFlags.Peek) == 0)
                            {
                                // Client disconnected
                                return false;
                            }
                            else
                            {
                                return true;
                            }
                        }
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                catch
                {
                    return false;
                }
            }
        }

You can call it simply from your code then with something like: client = new SimpleTcpClient();

        private void btnTest_Click(object sender, EventArgs e)
        {
            if (client.IsConnected)
            {
                MessageBox.Show("You are Connected");
            }
            else
            {
                MessageBox.Show("NO CONNECTION!");
            }

Hope that helps

Cheers!

PhyoeBlitz commented 3 years ago

@avcengineer You should Pull request.