c# – 如何检查连接是否打开

当我试图避免使用Thread.sleep(400)时,我遇到了问题

我的代码是这样的:

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

和我的send()方法:

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方法:

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

有没有办法检查流是否准备好使用?

最佳答案 虽然你的代码正在运行,但我想指出有关流的这些代码

GetStream()仅在2种情况下返回异常,这些异常为(Source):

> InvalidOperationException – TcpClient未连接到远程主机.
> ObjectDisposedException – 已关闭TcpClient.

因此,如果您满足这两个条件,您的流应该可用

在代码中编写异常逻辑总是很好,原因与另一方在代码中存在错误的原因相同.

在你自己的connect()方法中,你应该找出异常并通知被调用函数连接失败或将异常抛回调用函数并使用try catch来处理它.因此,在成功的情况下,您将始终获得您的流.

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
}

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);
            throw;
        }
        return clientSocket;
    }
点赞