C# WinForm UDP 发送和接收消息


代码如下:

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

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        UdpClient client = new UdpClient();
        public Form1()
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            Thread recvThread = new Thread(RecvMsg);
            recvThread.IsBackground = true;
            recvThread.Start();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string ip = textBox1.Text.Trim();
            string port = textBox2.Text.Trim();
            if (ip == null || port == null)
            {
                return;
            }
            IPEndPoint host = new IPEndPoint(IPAddress.Parse(ip),Convert.ToInt32(port));

            client.Connect(host);
            richTextBox1.Text = "已连接\n";
            textBox1.Enabled = false;
            textBox2.Enabled = false;
            button1.Enabled = false;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (client == null)
            {
                return;
            }
            string content = richTextBox2.Text.Trim();
            if (content == "" || content == null)
            {
                return;
            }
            byte[] buff = Encoding.UTF8.GetBytes(content);
            int v = client.Send(buff,buff.Length);
            richTextBox1.Text += content + "\n";
            richTextBox2.Text = null;
        }

        UdpClient recvClient = new UdpClient(new IPEndPoint(IPAddress.Parse("192.168.1.237"),40477));//接收方的IP
        private void RecvMsg()
        {
            while (1==1)
            {
                IPEndPoint remoteHost = null;
                byte[] recvByte = recvClient.Receive(ref remoteHost);
                string msg = Encoding.UTF8.GetString(recvByte);
                richTextBox1.Text += msg+"\n";
            }
        }
    }
}

  界面以及结果: