2015-06-18 62 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为您提供简单的基于流的界面时,无需使用原始套接字。

相关问题