2016-11-16 121 views
0

對WinForms不適用,但不適用於ASP.NET或C#。試圖製作客戶端/服務器應用程序。成功地從服務器上的客戶端接收數據,但在服務器程序winform上顯示它有麻煩。代碼如下:在WINFORM中將文本寫入文本框的文本屬性

服務器應用程序的代碼:

using System; 
using System.Windows.Forms; 
using System.Net.Sockets; 
using System.Net; 

namespace Server_App 
{ 
    public partial class Form1 : Form 
    { 

     public Form1() 
     { 
      InitializeComponent(); 
     } 
     private void button1_Click(object sender, EventArgs e) 
     { 
      IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 1234); //configure host 
      TcpListenerEx listener = new TcpListenerEx(ep); //set host to listen 
      if (!listener.Active) 
      { 
       listener.Start(); 
      } 
      while (true) 
      { 
       const int byteSize = 1024 * 1024; 
       byte[] message = new byte[byteSize]; 
       var s = listener.AcceptTcpClient(); 
       s.GetStream().Read(message, 0, byteSize); //obtaining network stream and receiving data through .Read() 
       message = cleanMessage(message);     
       string g = System.Text.Encoding.UTF8.GetString(message); 
       addMessage(g);  
      } 
     } 

     private void addMessage(string m) 
     { 
       this.textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + m; 
     } 

     private byte[] cleanMessage(byte[] rawMessageByte) 
     { 
      byte[] cleanMessage = rawMessageByte.Where(b => b != 0).ToArray(); 
      return cleanMessage; 
     } 
    } 
} 

客戶端應用代碼:按計劃,除了對服務器程序的Form1的文本框顯示接收到的數據

using System; 
using System.Net.Sockets; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace ClientApp 
{ 
    public partial class ClientApp : Form 
    { 
     public ClientApp() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      var message = System.Text.Encoding.UTF8.GetBytes(txtFromClient.Text);    
      using (var client = new TcpClient("127.0.0.1", 1234))//make connection with the host 
      { 
       NetworkStream stream = client.GetStream();/*obtain network stream*/     
       stream.Write(message, 0, message.Length); 
      } 
     } 

     private void textBox1_Click(object sender, EventArgs e) 
     { 
      txtFromClient.Text = ""; 
     } 
    } 
} 

一切正在發生的事情。在調試時,我確認了this.textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + m;行的變量m中收到的正確值。唯一的問題是,該值無法顯示,因此在服務器程序的Form1上可見。

有人可以請幫忙。

+1

你的文本框支持多行嗎? –

+0

@AlfieGoodacre對於服務器應用程序代碼的Form1上的textBox1,Multiline被設置爲'true'。是。 – Jogi

+4

您的點擊處理程序在'while(true)'循環中接收消息。它永遠不會退出,然後控件永遠不會有機會刷新(並且應用程序將掛起)。將它移動到一個'BackgroundWorker'。另一個_minor_事物:你不需要同時調用Dispose()和Close(),它可以用'using'來簡化。我相信還有其他問題關於同樣的問題(關閉這個像笨蛋),但現在找不到它 –

回答

1

的幫助和指導,從@AdrianoRepetti,解決給定的問題,通過下面的代碼就坐滿:

using System; 
using System.Windows.Forms; 
using System.Net.Sockets; 
using System.Net; 
using System.Linq; 

namespace Server_App 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
      backgroundWorker1.WorkerReportsProgress = true; 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 1234); //configure host 
      if(!backgroundWorker1.IsBusy) 
      { 
       backgroundWorker1.RunWorkerAsync(ep); //called to start a process on the worker thread and send argument (listener) to our workerprocess. 
      } 
     } 

     private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) 
     { 
      IPEndPoint ep = e.Argument as IPEndPoint; 
      TcpListenerEx listener = new TcpListenerEx(ep); 
      if (!listener.Active) 
      { 
       listener.Start(); 
      } 
      while (true) 
      { 
       try 
       { 
        const int byteSize = 1024 * 1024; 
        byte[] message = new byte[byteSize]; 
        using (var s = listener.AcceptTcpClient()) 
        { 
         s.GetStream().Read(message, 0, byteSize);//obtaining network stream and receiving data through .Read() 
         message = cleanMessage(message); 
         string g = System.Text.Encoding.UTF8.GetString(message); 
         backgroundWorker1.ReportProgress(0, g); 
        }      
       } 
       catch (Exception ex) 
       { 
        backgroundWorker1.ReportProgress(0, ex.Message); 
       } 
       finally 
       { 
        listener.Stop(); 
       } 
      }    
     } 

     private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e) 
     { 
      textBox1.AppendText(Environment.NewLine + ">> " + e.UserState); 
     } 

     private byte[] cleanMessage(byte[] rawMessageByte) 
     { 
      byte[] cleanMessage = rawMessageByte.Where(b => b != 0).ToArray(); 
      return cleanMessage; 
     } 
    } 
} 

希望它能幫助。

+0

只是一些小的事情:我把listener.Stop()放在finally {}塊內(因爲後臺線程會在表單處理時中斷)。在開始之前檢查backgroundWorker是否已經工作(backgroundWorker.IsBusy屬性)。 –

+0

完成........... – Jogi

+0

:)不要添加空的catch塊,它會_hide_錯誤。試試{} –

相關問題