2015-06-18 98 views
0

我跑我的服務器succsessfully但是當我打印,我以前打印在控制檯屏幕稱呼我是怎麼回事的數據,我想顯示所有的文本框,但它不顯示,而當我關閉來自客戶端的連接它顯示所有的信息。爲什麼會發生。?如何在服務器表單文本框中顯示數據?

這裏是我的代碼

public void GetData() 
    { 
    Form1 f = new Form1(); 
    string ipadd = getip(); 

    IPAddress ipAd = IPAddress.Parse("192.168.0.15"); //use local m/c IP address, and use the same in the client 
    // IPAddress ip = IPAddress.Parse(ipadd); 
    txtip.Text = ipAd.ToString(); 
    txtport.Text = "3030"; 
    /* Initializes the Listener */ 
    TcpListener myList = new TcpListener(ipAd, 3030); 

    /* Start Listeneting at the specified port */ 

    myList.Start(); 

    txtdata.Text = "The server is running at port 3030..."; 
    txtdata.Text = txtdata.Text + Environment.NewLine + "The local End point is :" + myList.LocalEndpoint; 
    txtdata.Text = txtdata.Text + Environment.NewLine + "Waiting for a connection....."; 



    Socket s = myList.AcceptSocket(); 

    txtdata.Text = txtdata.Text + Environment.NewLine +"Connection accepted from " + s.RemoteEndPoint; 
    // txtdata.Text = "Connection accepted from " + s.RemoteEndPoint; 

    } 

看代碼當我寫在控制檯上的數據它的工作原理,但同樣我要打印txtdata(文本框),但它不打印,直到連接關閉上述由客戶。

回答

0

你阻塞UI線程。在你的方法完成執行之前,UI不能更新,因爲它只能從UI線程更新。

你最好要使用異步I/O而不是阻塞UI線程。或者,在最壞的情況下,使用單獨的線程來處理通信。

var listener = new TcpListener(IPAddress.Any, 24221); 
listener.Start(); 

txtdata.Text = "The server is running..."; 

var client = await listener.AcceptTcpClientAsync(); 

此代碼避免阻塞UI線程 - 相反,UI線程可以自由地做任何事需要做,直到客戶端連接,這將導致代碼執行恢復在await點,再度上UI線程。

此外,嘗試使用可用的最高抽象 - 在這種情況下,AcceptTcpClient而不是AcceptSocket。當TcpClient爲您提供簡單的基於流的界面時,無需使用原始套接字。

相關問題