2013-04-26 73 views
0

我知道這對某些人來說可能是一個基本問題,所以請客氣一點。udp監聽器正在等待數據

以下解釋我的問題。在我的電腦上,我有Visual Studio 2010,其中有一個c#程序正在運行,我有一個udp監聽器在udp端口等待udp數據(可以說端口:85)。

UdpClient listener = null; 
try 
{ 
    listener = new UdpClient((int)nudPort.Value); 
    if (listener.Available > 0) 
    { ...... 
    } 
} 

誰能告訴我一個方法(任何程序)的,我可以在此端口發送UDP數據,以便我的C#程序可以在使用同一臺計算機檢測。

+1

使用另一個C#程序? – Guy 2013-04-26 12:32:03

+0

嗯我想你是對的。會給它一個嘗試 – aaaa 2013-04-26 12:35:57

回答

0

你試過Netcat

NC -u your_server_name_here 85 < - 其中85是你的監聽端口

檢查Wikipedia.org如何使用它。對於如何爲例發送客戶端和服務器之間的UDP包

+0

非常感謝! – aaaa 2013-04-26 12:57:09

0

下面的代碼會給你一個想法

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

namespace WindowsFormsApplication1 
{ 
    public partial class Form4 : Form 
    { 
     private Thread _listenThread; 
     private UdpClient _listener; 

     public Form4() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      this._listenThread = new Thread(new ThreadStart(this.StartListening)); 
      this._listenThread.Start(); 
     } 

     private void StartListening() 
     { 

      IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 35555); 
      IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); 

      this._listener = new UdpClient(localEndPoint); 

      try 
      { 
       do 
       { 
        byte[] received = this._listener.Receive(ref remoteIpEndPoint); 

        MessageBox.Show(Encoding.ASCII.GetString(received)); 

       } 
       while (this._listener.Available == 0); 
      } 
      catch (Exception ex) 
      { 
       //handle Exception 
      } 
     } 

     private void button2_Click(object sender, EventArgs e) 
     { 
      IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 35556); 
      IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 35555); 

      UdpClient caller = new UdpClient(localEndPoint); 

      caller.Send(Encoding.ASCII.GetBytes("Hello World!"), 12, remoteIpEndPoint); 

      caller.Close(); 
     } 

     protected override void OnFormClosing(FormClosingEventArgs e) 
     { 
      base.OnFormClosing(e); 

      this._listener.Close(); 

      this._listenThread.Abort(); 
      this._listenThread.Join(); 

      this._listenThread = null; 
     }  
    } 
} 
+0

非常感謝! – aaaa 2013-04-26 14:02:25