udp listener waiting for data

2019-08-26 08:17发布

I know it might be a basic question for some people so please be kind.

Following explains my problem. On my computer, i have visual studio 2010 in which a c# program is running where I have a udp listener waiting for udp data on a udp port (lets say port:85).

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

Can anybody tell me a way (any program ) by which i can send udp data on this port so that my c# program can detect it using the same computer.

标签: c# udp
2条回答
成全新的幸福
2楼-- · 2019-08-26 08:28

Have you tried Netcat

nc -u your_server_name_here 85 <- where 85 is your listening port

Check Wikipedia.org on how to use it. There is an example on how to send UDP packages between client and server

查看更多
做自己的国王
3楼-- · 2019-08-26 08:48

The following code will give you an idea

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;
        }    
    }
}
查看更多
登录 后发表回答