2014-01-15 28 views
0

目前我正在將我的客戶端同步連接到服務器。
但是,服務器有時不可用,所以我認爲使用異步會更好,因此我可以收集和格式化稍後要發送的數據。我發現我正在尋找的方法可能是TcpClient.BeginConnect
不幸的是,我對於異步操作完全陌生,所以參數很奇怪。
舉例:我是否有一個特定的原因需要單獨使用IP和端口,即不使用IPEndPoint?
然而更重要的問題是:AsyncCallback和Object,這些是什麼?
我是否需要更改我的服務器上的任何內容?
我想我明白,snyc或asnyc是本地選擇,不會影響對方,至少不會影響兼容性。
最後:Here我讀了關於關鍵字asnyc並等待:在哪裏使用它們以及如何使用它們?async TcpClient.Connect()如何使用它?

這裏有一個小的僞代碼來證明什麼,我有什麼,我想

private static void send(string msg) { 
    TcpClient cli = new TcpClient(localEP); 
    bool loop = true; 
    while(loop) {  //trying over and over till it works 
     try {   //is bad practice and inefficient 
      cli.Connect(remoteEP); 
     } catch (Exception) { 
      ; 
     } 
     if(cli.Connected) 
      break; 
    } 
    var blah = doOtherThings(msg); 
    useTheClient(blah); 
} 

現在我多麼希望它的工作

private static void send(string msg) { 
    TcpClient cli = new TcpClient(localEP); 
    cli.BeginConnect(remoteEP); //thread doesn't block here anymore + no exceptions 
    var blah = doOtherThings(msg); //this now gets done while cli is connecting 
    await(cli.connect == done) //point to wait for connection to be established 
    useTheClient(blah); 
} 

回答

1

你需要創建一個新的AsyncCallback並將其設置爲一個特定的空白,在TcpClient完成連接到主機後,將執行某些操作。您可能還需要檢查TcpClient連接是否成功通過檢查TcpClient.Connected

下面的例子說明端口異步TcpClient連接到google.com的價值80

static TcpClient cli = new TcpClient(); //Initialize a new TcpClient 
static void Main(string[] args) 
{ 
    send("Something"); 
    Console.ReadLine(); 
} 
private static void doSomething(IAsyncResult result) 
{ 
    if (cli.Connected) //Connected to host, do something 
    { 
     Console.WriteLine("Connected"); //Write 'Connected' 
    } 
    else 
    { 
     //Not connected, do something 
    } 
    Console.ReadLine(); //Wait for user input 
} 
private static void send(string msg) 
{ 
    AsyncCallback callBack = new AsyncCallback(doSomething); //Set the callback to the doSomething void 
    cli.BeginConnect("google.com", 80, callBack, cli); //Try to connect to Google on port 80 
} 

這裏有一個更好的方法來做你在評論中描述的內容

System.Threading.Thread newThread = new System.Threading.Thread((System.Threading.ThreadStart)delegate { 
//Do whatever you want in a new thread 
    while (!cli.Connected) 
    { 
     //Do something 
    } 
}); 
newThread.Start(); //Start executing the code inside the thread 
//This code will still run while the newThread is running 
Console.ReadLine(); //Wait for user input 
newThread.Abort(); //Stop the thread when the user inserts any thing 
+0

好的,這已經看起來比我之前發現的任何東西都簡單。這意味着:「當連接時,調用'callback'並傳遞''connected」'「,直到代碼進一步被執行。我到目前爲止是否正確?除了只有void類型之外,對回調函數的設計是否有任何限制,比如只有一個參數是IAsyncResult? 現在我怎麼能定義我不想在asnyc事件通過之前通過的點,即它通過哪個點連接並且我不能再做任何其他事情? – Mark

+1

@Mark是的,代碼將在您的應用程序正常運行時在後臺執行。然後,當TcpClient完成連接或嘗試連接時,它將運行回調void。回調void然後通過檢查'cli.Connected'值來檢查TcpClient是否成功連接,並且抱歉,但我沒有真正回答你最後的問題,你是什麼意思? –

+0

比方說,我想在啓動我的程序時建立連接權限,但不能完成特定的任務,只需完成它。然後我做各種事情,然後我想要使用客戶端。當它沒有連接,但我崩潰,所以在這裏我想等待它。有沒有一種簡單的方法來等待,而不是'while(!cli.Connected);'? – Mark

相關問題