2017-08-30 75 views
0

我有這樣的代碼,似乎停留在Socket client = listener.AcceptSocket();的TcpListener和客戶端在同一個窗體應用程序

此代碼工作正常在一個控制檯應用程序,但是當我嘗試在Windows使用它窗體應用程序不能正常啓動工作/窗口顯示不出來

這裏是我的代碼:

public Form1() 
    { 
     InitializeComponent(); 

     Listen(); 
    } 
    public void Listen() 
    { 
     try 
     { 
      IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); 

      Console.WriteLine("Starting TCP listener..."); 

      TcpListener listener = new TcpListener(ipAddress, 1302); 

      listener.Start(); 

      while (true) 
      { 
       Console.WriteLine("Server is listening on " + listener.LocalEndpoint); 

       Console.WriteLine("Waiting for a connection..."); 

       Socket client = listener.AcceptSocket(); // <----- PROBLEM 

       Console.WriteLine("Connection accepted."); 

       Console.WriteLine("Reading data..."); 

       byte[] data = new byte[100]; 
       int size = client.Receive(data); 
       Console.WriteLine("Recieved data: "); 
       for (int i = 0; i < size; i++) 
        Console.Write(Convert.ToChar(data[i])); 

       Console.WriteLine(); 

       client.Close(); 
      } 

      listener.Stop(); 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine("Error: " + e.StackTrace); 
      Console.ReadLine(); 
     } 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     if (richTextBox1.Text != "") 
     { 
      textToSend = richTextBox1.Text; 
      run = true; 
     } 
     else 
     { 
      MessageBox.Show("Box Cant Be Empty"); 
      run = false; 
     } 
     if (run) 
     { 
      try 
      { 
       TCPclient = new TcpClient(SERVER_IP, PORT_NO); 
       nwStream = TCPclient.GetStream(); 
      } 
      catch 
      { 

      } 
      byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend); 

      //---send the text--- 
      MessageBox.Show("Sending : " + textToSend); 
      nwStream.Write(bytesToSend, 0, bytesToSend.Length); 

     } 
    } 

回答

0

控制檯將繼續輸出,即使正在運行的代碼是忙。它被塗在你的應用程序之外。

您正在使用的窗體窗體需要主應用程序線程可用於更新和繪製窗體。您應該查看異步/等待模式並學習如何使用它來阻止IO調用。這個話題太大了,不能給你一個簡單的答案,但是你可以在這裏找到一些關於async/await的信息:https://msdn.microsoft.com/library/hh191443(vs.110).aspx雖然有些googlefu可能會找到更好的文章。

一些額外的信息可以在這裏找到關於用戶界面的響應: https://msdn.microsoft.com/en-us/library/windows/desktop/dd744765(v=vs.85).aspx

0

Socket client = listener.AcceptSocket();正在等待傳入數據包。 除非和直到收到一個,否則WinForm UI將不會顯示,因爲您在窗體構造函數中調用Listen();,從而阻塞了主線程(UI)。

在單獨的線程中運行Listen();

+0

好ive做到了這一點,它的工作,但我該如何改變該線程以外的變量? FX。 MessageBox.Show();或ListBox1.Items.Add(); –

+0

請編輯問題,並解釋你需要什麼 –

+0

其解釋相當不錯,如果我需要改變該線程以外的變量不工作 –

相關問題