2012-05-23 208 views
2

我用下面的代码创建一个TCP监听器:TCP监听开始异常

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

我开始用下面的代码来监听TCP设备:

TCPListener.Start(); 

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

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

回答

5

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

3

抓住它并显示你自己的错误信息。

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

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

好,考虑到你在谈论特殊的情况下,只处理与合适try/catch块的异常,并通知用户有关的事实。

2

把它放在try catch块。

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

} catch (SocketException e) { 
    // Error handling routine 
    Console.WriteLine(e.ToString()); 
} 
+0

你可能赶上了太多的例外...... –

2

使用try-catch块并捕获SocketException。

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

获取异常并不是一个好主意检查端口是否在使用中。使用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. 

详情请阅读this

处理异常,你将使用try/catch作为哈比卜建议

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