TcpClient.BeginConnect(主机、端口、空、空);随机成功

TcpClient.BeginConnect(host, port, null, null); gives random success

在我的代码中,我尝试使用计时器连接到中继板,该计时器在每次滴答时调用一个方法。问题是当我 运行 我的应用程序时,我在前 3-4 个滴答声中成功建立了连接。但是,之后它无法连接。我无法弄清楚我的代码有什么问题。任何帮助,将不胜感激。我正在与 asp.net

合作

调用的方法:

private void open_ethernet_connection()
{
    byte connected = 0;

    TcpClient client = new TcpClient();
    try
    {

        IAsyncResult result = client.BeginConnect(textBox_IP.Text.Substring(0, textBox_IP.Text.IndexOf(",")), GlobalClass.port, null, null);
        bool success = result.AsyncWaitHandle.WaitOne(1000, true);

        if (!success)
        {
            connected = 0;
            client.Close();
            Response.Write("Failed to connect");
        }
        else connected = 1;

        if (connected == 1)
        {
            ns = client.GetStream();
            ns.ReadTimeout = 1000;
            SerBuf[0] = (byte)commands.GET_VER;     // get version command for ETH RLY16/02, returns software version
            transmit(1);
            receive(3);
            module_version = SerBuf[2];  //print the software version on screen
            device_found = true;
        }
    }
    catch (SocketException)
    {
        if (selected_port == "Custom IP")
        {
            Response.Write("Unable to connect to module at " + GlobalClass.ipaddress);
        }
        else Response.Write("Unable to connect to module at " + selected_port);
        return;
    } 
}

如果连接成功,您永远不会关闭连接。

考虑使用 using https://msdn.microsoft.com/sv-SE/library/yh598w02.aspx

using (TcpClient client = new TcpClient())
{
   Other code here...
}

这样你的 TcpClient 总是被释放,你不必调用 .Close()