C#winform UDP通信 发送和接收信息

时间:2025-04-18 08:06:55
using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;

namespace UDP测试_客户端
{
    public partial class ClientForm2 : Form
    {
        public ClientForm2()
        {
            InitializeComponent();
        }
        static Socket client;
        Thread t;
        Thread t2;
        string recv;
        private void btnSend_Click(object sender, EventArgs e)
        {
            EndPoint point = new IPEndPoint(("192.168.48.1"), 6001);
            string msg = ;
            (Encoding.(msg), point);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
             = recv ;
        }

        private void ClientForm2_Load(object sender, EventArgs e)
        {
            client = new Socket(, , );
            (new IPEndPoint((), ()));

            t = new Thread(sendMsg);
            //();

            t2 = new Thread(ReciveMsg);
            ();

            ();
        }
        /// <summary>
        /// 向特定ip的主机的端口发送数据报
        /// </summary>
        void sendMsg()
        {
            EndPoint point = new IPEndPoint(("192.168.48.1"), 6001);
            while (true)
            {
                string msg = ;
                ((msg), point);
            }
        }
        /// <summary>
        /// 接收发送给本机ip对应端口号的数据报
        /// </summary>
        void ReciveMsg()
        {
            while (true)
            {
                EndPoint point = new IPEndPoint(, 0);//用来保存发送方的ip和端口号
                byte[] buffer = new byte[1024];
                int length = (buffer, ref point);//接收数据报
                recv += Encoding.(buffer, 0, length);
                recv += "\r\n";
                // += recv;
            }
        }

        private void ClientForm2_FormClosing(object sender, FormClosingEventArgs e)
        {
            ();
            ();
            ();
        }
    }
}
         UDP通信不需要建立连接。