C# 中的 TCP 侦听器启动异常

本文关键字:启动 异常 侦听器 TCP 中的 | 更新日期: 2023-09-27 18:35:09

我使用以下代码创建一个TCP侦听器:

TCPListener = new TcpListener(IPAddress.Any, 1234);

我使用以下代码开始侦听 TCP 设备:

TCPListener.Start();

但是在这里,我无法控制端口是否正在使用中。当端口正在使用中时,程序会给出一个例外:"通常只允许每个套接字地址(协议/网络地址/端口)使用一次。

如何处理此异常?我想警告用户端口正在使用中。

C# 中的 TCP 侦听器启动异常

TCPListener.Start(); 周围放置一个 try/catch 块并捕获 SocketException。此外,如果您要从程序中打开多个连接,那么最好在列表中跟踪连接,并在打开连接之前查看是否已打开连接

获取异常以检查端口是否正在使用中不是一个好主意。 使用 IPGlobalProperties 对象获取TcpConnectionInformation对象的数组,然后可以查询有关终结点 IP 和端口的信息。

 int port = 1234; //<--- This is your value
 bool isAvailable = true;
 // Evaluate current system tcp connections. This is the same information provided
 // by the netstat command line application, just in .Net strongly-typed object
 // form.  We will look through the list, and if our port we would like to use
 // in our TcpClient is occupied, we will set isAvailable to false.
 IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
 TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
 foreach (TcpConnectionInformation tcpi in tcpConnInfoArray)
 {
   if (tcpi.LocalEndPoint.Port==port)
   {
     isAvailable = false;
     break;
   }
 }
 // At this point, if isAvailable is true, we can proceed accordingly.

有关详细信息,请阅读此内容。

为了处理异常,您将按照 habib 的建议使用 try/catch

try
{
  TCPListener.Start();
}
catch(SocketException ex)
{
  ...
}

捕获它并显示您自己的错误消息。

检查异常类型并在 catch 子句中使用此类型。

try
{
  TCPListener.Start();
}
catch(SocketException)
{
  // Your handling goes here
}

把它放在一个try catch块中。

try {
   TCPListener = new TcpListener(IPAddress.Any, 1234);
   TCPListener.Start();
} catch (SocketException e) {
  // Error handling routine
   Console.WriteLine( e.ToString());
 }

使用 try-catch 块并捕获 SocketException。

try
{
  //Code here
}
catch (SocketException ex)
{
  //Handle exception here
}

好吧,考虑到您谈论的是特殊情况,只需使用适当的try/catch块来处理该异常,并告知用户一个事实。