【问题标题】:TcpListener constant error Only one usage of each addressTcpListener 常量错误 每个地址只使用一次
【发布时间】:2018-01-23 01:55:01
【问题描述】:

我正在尝试使用 TcpListener。每次我尝试启动侦听器时,我都会收到地址已在使用中的错误。我查看了 netstat,但在该端点(IP 地址、端口)上看不到任何东西。

 class Program
{
    static void Main(string[] args)
    {
        IPAddress ip = IPAddress.Parse("127.0.0.1");
        TcpListener listener = new TcpListener(ip, 58000);
        listener.Start();
    }
}

当我每次运行时都会出错。

【问题讨论】:

  • 几乎可以肯定,您的程序的旧副本仍在运行。或者其他人在监听端口。使用 sysinternals tcpview 找出答案。 docs.microsoft.com/en-us/sysinternals/downloads/tcpview
  • 看起来该端口正在被另一个进程使用。尝试执行 netstat -nt 命令并检查端口 58000 是否被任何其他进程使用
  • tcpview 解决了这个问题。太好了

标签: c# sockets tcplistener


【解决方案1】:

错误很明显,另一个进程(可能是因为您的程序未完成 exe)绑定了您要侦听的同一端口。尝试监听不同的端口,看看情况;

IPAddress ip = IPAddress.Parse("127.0.0.1");
TcpListener listener = new TcpListener(ip, 58001);
listener.Start();

另外,我强烈建议您使用TcpView 来检查分配的端口。

【讨论】:

    【解决方案2】:

    您肯定有另一个进程(很可能与您尝试运行的进程相同)在后台运行,因此您无法打开端口。尝试打开并确保关闭连接:

    public static void Main()
      { 
        TcpListener server=null;   
        try
        {
          Int32 port = 58000;
          IPAddress localAddr = IPAddress.Parse("127.0.0.1");
    
          // TcpListener server = new TcpListener(port);
          server = new TcpListener(localAddr, port);
    
          // Start listening for client requests.
          server.Start();
    
          // DO ALL YOUR WORK
        }
        catch(SocketException e)
        {
          Console.WriteLine(e.ToString());
        }
        finally
        {
           // Stop listening for new clients.
           server.Stop();
        }
      }   
    

    【讨论】:

    • 我会将 try catch 块和 finally 块添加到我的逻辑中
    猜你喜欢
    • 2019-08-01
    • 2023-03-30
    • 1970-01-01
    • 2016-02-02
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    相关资源
    最近更新 更多