C# 简单的UDP数据接收与发送 源码实例

以下核心代码
public partial class Form1 : Form
{//更多相关源码请防问 www.luofenming.com
    public Form1()
    {
        InitializeComponent();
    }

    /// <summary>
    /// 用于UDP发送的网络服务类
    /// </summary>
    private UdpClient udpcRecv = null;

    private IPEndPoint localIpep = null;

    /// <summary>
    /// 线程:不断监听UDP报文
    /// </summary>
    private Thread thrRecv;

    public void StartReceive(string IP, int port)
    {
        if (thrRecv == null || !thrRecv.IsAlive) // 未监听的情况,开始监听
        {
            localIpep = new IPEndPoint(IPAddress.Parse(IP), port); // 本机IP和监听端口号
            udpcRecv = new UdpClient(localIpep);
            thrRecv = new Thread(ReceiveMessage);
            thrRecv.IsBackground = true;
            thrRecv.Start();
            DisplayData("UDP监听器已成功启动");
        }
    }

    public void StopReceive()
    {
        if (thrRecv != null && thrRecv.IsAlive)
        {
            thrRecv.Abort(); // 必须先关闭这个线程,否则会异常
            udpcRecv.Close();
            DisplayData("UDP监听器已成功关闭");
        }
    }

    /// <summary>
    /// 接收数据
    /// </summary>
    /// <param name="obj"></param>
    private void ReceiveMessage(object obj)
    {
        while (true)
        {
            try
            {
                byte[] bytRecv = udpcRecv.Receive(ref localIpep);
                string message = Encoding.UTF8.GetString(bytRecv, 0, bytRecv.Length);
                DisplayData(string.Format($"{localIpep}[{message}]"));

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                break;
            }
        }
    }



    /// <summary>
    /// 发送信息
    /// </summary>
    /// <param name="obj"></param>
    private void SendMessage(string IP, int port, string message)
    {
        try
        {
            byte[] sendbytes = Encoding.UTF8.GetBytes(message);
            IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Parse(IP), port); // 发送到的IP地址和端口号
            udpcRecv.Send(sendbytes, sendbytes.Length, remoteIpep);
        }
        catch { }
    }

    private void DisplayData(string msg)
    {
        this.BeginInvoke(new Action(
            () => { textBox3.AppendText($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}\r\n{msg}\r\n"); }
                 )
            );  
    }

    //打开UDP
    private void button1_Click(object sender, EventArgs e)
    {
        int port;
        int.TryParse(textBox2.Text, out port);
        StartReceive(textBox1.Text, port);
        IsEnabled(false);
    }
    //发送信息
    private void button2_Click(object sender, EventArgs e)
    {
        int port;
        int.TryParse(textBox5.Text, out port);
        SendMessage(textBox6.Text, port, textBox4.Text);
        IsEnabled(true);
    }

    //关闭UDP
    private void button3_Click(object sender, EventArgs e)
    {
        StopReceive();
    }
    private void IsEnabled(bool isEnabled)
    {
        button1.Enabled = isEnabled;
        button2.Enabled = !isEnabled;
        button3.Enabled = !isEnabled;
    }
}
源码下载地址: https://pan.baidu.com/s/1wz1H3mxh0VBD38nYE2n0eA 提取码: bbck

评论