How to check if a connection is open

I have a problem when I try to avoid using Thread.sleep(400) my code looks like this:

System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
clientSocket = Connect(IP, Port);
Thread.Sleep(400);

NetworkStream networkStream = clientSocket.GetStream();
Send(networkStream, "My Data To send");
networkStream.Flush();

and my send () method:

public static void Send(NetworkStream networkStream, string Data)
{
    int range = 1000;
    int datalength = 0;
    foreach (string data in Enumerable.Range(0, Data.Length / range).Select(i => Data.Substring(i * range, range)))
    {
        byte[] outStream = System.Text.Encoding.ASCII.GetBytes(data);
        networkStream.Write(outStream, 0, outStream.Length);
        datalength = datalength + range;
        Thread.Sleep(50);
    }
    byte[] LastoutStream = System.Text.Encoding.ASCII.GetBytes(Data.Substring(datalength, Data.Length - datalength) + "$EOS$\r\n");
    networkStream.Write(LastoutStream, 0, LastoutStream.Length);
}

Connect method:

 protected static System.Net.Sockets.TcpClient Connect(string Ip, int Onport)
    {
        //start connection
        System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
        try
        {
            clientSocket.Connect(Ip, Onport);
        }
        catch
        {
            clientSocket.Connect("LocalHost", Onport);
        }
        return clientSocket;
    }

Is there a way to check if a thread is ready for use?

+4
source share
1 answer

Even though your code works, I would like to point to them regarding the stream

GetStream()returns an exception only in 2 cases, and these exceptions ( Source ):

  • InvalidOperationException - TcpClient is not connected to the remote host.

  • ObjectDisposedException - TcpClient is closed.

So, your flow should be accessible if you meet these two conditions

, , .

connect() , , . .

try{
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
clientSocket = Connect(IP, Port);
//Thread.Sleep(400);

NetworkStream networkStream = clientSocket.GetStream();
Send(networkStream, "My Data To send");
networkStream.Flush();
}catch(Exception E)
{
 //Log
 //Its always best to catch the actual exception than general exception
 //Handle gracefully
}

,

 protected static System.Net.Sockets.TcpClient Connect(string Ip, int Onport)
    {
        //start connection
        System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
        try
        {
            clientSocket.Connect(Ip, Onport);
        }
        catch
        {
            //clientSocket.Connect("LocalHost", Onport);
            throw;
        }
        return clientSocket;
    }
+2

Source: https://habr.com/ru/post/1527723/


All Articles