1
我有一個棘手的問題需要解決。使用我的C#應用程序,我正在建立到通過以太網連接的設備的TCP客戶端連接。用戶可以提供一個IP和一個端口到提供的字段,並且只需按下按鈕即可連接到設備。如果用戶輸入錯誤的IP /端口號,我有一個try/catch塊用於異常處理。可以檢查是否有可用的連接可用於給定的IP和C#端口
//Constructor
public DepotETHInterface(string ip, int port)
{
ipEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
connectionActive = false;
}
public void Connect()
{
try
{
// Connect to the remote endpoint.
client.BeginConnect(ipEndPoint,new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
connectionActive = true;
Console.WriteLine("Response received : {0}", response);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
MessageBox.Show("Bitte geben Sie eine gültige IP und einen Port an", "Keine Verbindung vorhanden", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
但由於某些原因,它需要年齡顯示情況下,它運行到catch塊的消息框。有沒有更好的解決方法?
如果輸入無效的IP,它會超時我想象。什麼是超時時間? – DiskJunky
@DiskJunky哈哈,直到你說我永遠不會設置超時時間。也許這是解決方案。感謝提示:)我是noob xD – Isuru
您可以使用PING來測試設備是否在以太網上。對PING的響應包含設備的MAC(製造商,型號,序列號),因此您知道IP適用於正確的設備。 – jdweng