如何检查连接是否打开

5

在避免使用 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 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;
    }

有没有办法检查流是否可以使用?


2
你的流应该立即准备好使用。如果没有Sleep,你的问题会如何表现? - 500 - Internal Server Error
1
你能展示一下你的Connect方法的内容吗? - Sacrilege
如果你希望避免使用它 =D,就删除Thread.Sleep(4000) - Sinatr
1
你连接的是哪个服务?也许你在服务指示准备好之前就发送了数据? - Janus Tøndering
1
我问了那个编写我正在连接的程序的人,他在他的代码中发现了一个错误。现在它可以正常工作而无需休眠。 - Rene Nielsen
显示剩余5条评论
1个回答

2

虽然你的代码可以运行,但我想指出以下与流相关的问题:

GetStream()仅在两种情况下返回异常,这些异常是(来源):

  1. InvalidOperationException- TcpClient未连接到远程主机。

  2. 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
}

连接方法或者您可以省略异常以回退到调用方。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接