2012-03-02 142 views
4

嘿傢伙我想了解TCP服務器/客戶端交互。我想知道如何隨時使用GUI來監聽端口。目前我使用此代碼:我將如何在GUI上持續監聽端口?

private void Form1_Load(object sender, EventArgs e) 
    { 
     CreateServer(); 
    } 

    void CreateServer() 
    { 
     TcpListener tcp = new TcpListener(25565); 
     tcp.Start(); 

     Thread t = new Thread(() => 
     { 

      while (true) 
      { 
       var tcpClient = tcp.AcceptTcpClient(); 

       ThreadPool.QueueUserWorkItem((_) => 
       { 
        Socket s = tcp.AcceptSocket(); 

        console.Invoke((MethodInvoker)delegate { console.Text += "Connection esatblished: " + s.RemoteEndPoint + Environment.NewLine; }); 

        byte[] b = new byte[100]; 
        int k = s.Receive(b); 


        for (int i = 0; i < k; i++) 
        { 
         console.Text += Convert.ToChar(b[i]); 
         incoming += Convert.ToChar(b[i]); 
        } 

        MessageBox.Show(incoming); 

        console.Invoke((MethodInvoker)delegate { console.Text += incoming + Environment.NewLine; }); 

        list.Invoke((MethodInvoker)delegate { list.Items.Add(incoming); }); 

        ASCIIEncoding asen = new ASCIIEncoding(); 
        s.Send(asen.GetBytes("\n")); 

        tcpClient.Close(); 
       }, null); 
      } 
     }); 
     t.IsBackground = true; 
     t.Start(); 
    } 

任何幫助將是非常appreciateed。

+0

查看更新的答案 – sll 2012-03-02 14:41:28

回答

4

簡答 - 在單獨的線程/任務(TPL)中運行TCP偵聽器。 對於完整的工作解決方案,你還必須實現UI窗體的單獨線程到主線程的任何改變的調度,這是依賴於你正在使用的框架的特殊技術,我的意思是WPF/WinForms /無論如何。

下面的代碼適合我。之前閱讀TODO部分。

TODO:

  • 添加形成文本框,列表框,按鈕,讓市民:

    public System.Windows.Forms.TextBox console; 
    public System.Windows.Forms.ListBox incommingMessages; 
    private System.Windows.Forms.Button sendSampleDataButton; 
    

切入點:

private static Form1 form; 

[STAThread] 
static void Main() 
{ 
    Application.EnableVisualStyles(); 
    Application.SetCompatibleTextRenderingDefault(false); 

    form = new Form1(); 
    form.Load += OnFormLoad; 
    Application.Run(form); 
} 

private static void OnFormLoad(object sender, EventArgs e) 
{ 
    CreateServer(); 
} 

服務器:

private static void CreateServer() 
{ 
    var tcp = new TcpListener(IPAddress.Any, 25565); 
    tcp.Start(); 

    var listeningThread = new Thread(() => 
    { 
     while (true) 
     { 
      var tcpClient = tcp.AcceptTcpClient(); 
      ThreadPool.QueueUserWorkItem(param =>                
      {       
       NetworkStream stream = tcpClient.GetStream(); 
       string incomming;       
       byte[] bytes = new byte[1024]; 
       int i = stream.Read(bytes, 0, bytes.Length);             
       incomming = System.Text.Encoding.ASCII.GetString(bytes, 0, i); 
       form.console.Invoke(
       (MethodInvoker)delegate 
        { 
         form.console.Text += String.Format(
          "{0} Connection esatblished: {1}{2}", 
          DateTime.Now, 
          tcpClient.Client.RemoteEndPoint, 
          Environment.NewLine); 
        }); 

       MessageBox.Show(String.Format("Received: {0}", incomming)); 
       form.incommingMessages.Invoke((MethodInvoker)(() => form.incommingMessages.Items.Add(incomming))); 
       tcpClient.Close(); 
      }, null); 
     } 
    }); 

    listeningThread.IsBackground = true; 
    listeningThread.Start(); 
} 

客戶

private void button1_Click(object sender, EventArgs e) 
{ 
    Connect("localhost", "hello localhost " + Guid.NewGuid()); 
} 

static void Connect(String server, String message) 
{ 
    try 
    {    
     Int32 port = 25565; 
     TcpClient client = new TcpClient(server, port);    
     Byte[] data = System.Text.Encoding.ASCII.GetBytes(message); 
     NetworkStream stream = client.GetStream(); 

     // Send the message to the connected TcpServer. 
     stream.Write(data, 0, data.Length);         
     stream.Close(); 
     client.Close(); 
    } 
    catch (ArgumentNullException e) 
    { 
     Debug.WriteLine("ArgumentNullException: {0}", e); 
    } 
    catch (SocketException e) 
    { 
     Debug.WriteLine("SocketException: {0}", e); 
    }   
} 

截圖:

enter image description here

+0

我沒有看到任何對tpl的引用。你使用tpl嗎? – 2013-03-08 08:55:44

2

創建一個線程,開始它來聽&不停止服務器

void CreateServer() 
{ 
    TcpListener tcp = new TcpListener(25565); 
    tcp.Start(); 

    Thread t = new Thread(()=> 
    { 
     while (true) 
     { 
      var tcpClient = tcp.AcceptTcpClient(); 
      ThreadPool.QueueUserWorkItem((_) => 
      { 
       //Your server codes handling client's request. 
       //Don't access UI control directly here 
       //Use "Invoke" instead. 
       tcpClient.Close(); 
      },null); 
     } 
    }); 
    t.IsBackground = true; 
    t.Start(); 
} 
+0

嘿,我更新了我的代碼,可以查看它嗎?它似乎並沒有工作,可能是因爲我在這方面不熟悉。 – 2012-03-02 12:28:38

+2

'它似乎沒有工作什麼是不工作?你會得到什麼錯誤? – 2012-03-02 12:54:46