udp监听器正在等待数据
问题描述:
我知道这对某些人来说可能是一个基本问题,所以请客气一点。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#程序可以在使用同一台计算机检测。
答
你试过Netcat
NC -u your_server_name_here 85 < - 其中85是你的监听端口
检查Wikipedia.org如何使用它。对于如何为例发送客户端和服务器之间的UDP包
+0
非常感谢! – aaaa 2013-04-26 12:57:09
答
下面的代码会给你一个想法
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
使用另一个C#程序? – Guy 2013-04-26 12:32:03
嗯我想你是对的。会给它一个尝试 – aaaa 2013-04-26 12:35:57