【问题标题】:TcpClient.BeginConnect(host, port, null, null); gives random successTcpClient.BeginConnect(主机,端口,空,空);随机成功
【发布时间】:2016-04-12 19:56:22
【问题描述】:

在我的代码中,我正在尝试使用计时器连接到继电器板,该计时器在每次滴答时都会调用一个方法。问题是当我运行我的应用程序时,我在前 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;
    } 
}

【问题讨论】:

  • 我认为这不是问题,但如果可能的话,您应该在处理完 TcpClient 后将其丢弃,请使用 using。此外,如果您要等待它与 WaitOne 同步,使用 Async 方法似乎毫无意义。
  • 定时器的时间间隔是多少?
  • @Peter 使用 client.Connect(host, port) 给出相同的结果。
  • @jgauffin 定时器的间隔为 2000 毫秒。
  • @Peter 非常感谢,你拯救了我的一天! client.Close() 完成了这项工作。

标签: c# asp.net tcpclient


【解决方案1】:

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

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

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

这样你的 TcpClient 总是被释放,你不必打电话给.Close()

【讨论】:

  • 我需要使用.Close(),因为建立的连接用于其他方法。但是感谢您的帮助! :)
  • 您可以将所有网络代码包装在一个具有所有逻辑的对象中,并在该对象上使用 dispose 模式。
猜你喜欢
  • 1970-01-01
  • 2017-07-22
  • 1970-01-01
  • 1970-01-01
  • 2013-10-12
  • 1970-01-01
  • 1970-01-01
  • 2011-01-19
  • 1970-01-01
相关资源
最近更新 更多