首页 文章

通常只允许使用每个套接字地址(协议/网络地址/端口)

提问于
浏览
2

我连接到Asp.Net中的TCP / IP端口,基本上我已经在我正在阅读的这个端口上附加了一个设备,它工作正常但是第二次当tcp监听器尝试启动时它会产生上述错误 . 可以任何身体指导我如何摆脱这个错误这里是我用来连接到TCP / IP端口的代码:

try
        {                
            byte[] ipaddress = new byte[4];
            string ip = ConfigurationManager.AppSettings["IP"].ToString();
            string[] ips = ip.Split('.');
            ipaddress[0] = (byte)Convert.ToInt32(ips[0]);
            ipaddress[1] = (byte)Convert.ToInt32(ips[1]);
            ipaddress[2] = (byte)Convert.ToInt32(ips[2]);
            ipaddress[3] = (byte)Convert.ToInt32(ips[3]);
            int portNumber = Convert.ToInt32(ConfigurationManager.AppSettings["Port"]);
            tcpListener = new TcpListener(new IPAddress(ipaddress), portNumber);
            tcpListener.Start();
            tcpClient = new TcpClient();
            tcpClient.NoDelay = true;
            try
            {
                System.Threading.Thread.Sleep(60000);
                tcpClient.ReceiveTimeout = 10;
                tcpClient = tcpListener.AcceptTcpClient();
            }
            catch (Exception ex)
            {
                tcpClient.Close();
                tcpListener.Stop();
            }
            NetworkStream networkStream = tcpClient.GetStream();
            byte[] bytes = new byte[tcpClient.ReceiveBufferSize];
            try
            {
                networkStream.ReadTimeout = 2000;
                networkStream.Read(bytes, 0, bytes.Length);
            }
            catch (Exception ex)
            {
                tcpClient.Close();
                tcpListener.Stop();
            }
            string returndata = Encoding.Default.GetString(bytes);
            tcpClient.Close();
            tcpListener.Stop();

            return returndata.Substring(returndata.IndexOf("0000000036"), 170);
        }
        catch (Exception ex)
        {
            if (tcpClient != null)
                tcpClient.Close();
            tcpListener.Stop();
            LogError("Global.cs", "ReceiveData", ex);
            ReceiveData();
        }

当它来到这一行tcpListener.Start();第二次然后它产生该错误“通常只允许使用每个套接字地址(协议/网络地址/端口)”

2 回答

  • 0

    如果这是循环或某事,请注意,如果您的代码没有触发任何异常,则不会关闭连接 . 仅在存在异常时才会关闭,该异常将由结尾 catch 块捕获

  • 1

    您不使用using关键字或finally块来确保关闭资源 .

    如果代码中的任何地方都存在异常,则可能不会进行清理 . 您的多个catch块可能会获得所有场景,但我不能通过阅读代码轻松判断 .

    使用需要清理的资源的一般首选模式是:

    using (MyResource res = new MyResource())
    {
       // Do Stuff
    }
    

    如果MyResource实现IDisposable,或

    try
    {
      MyResource res = new MyResource();
      // Do Stuff
    } catch (Exception ex)
    {
      // Whatever needs handing on exception
    }
    finally
    {
      res.Close(); // Or whatever call needs to be made to clean up your resource.
    }
    

相关问题