zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C# UDP接收和发送

c# 发送 UDP 接收
2023-09-11 14:16:45 时间


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.NET;
using System.Net.Sockets;
using System.Threading;

namespace WpfTest
{
    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            Thread thread1 = new Thread(new ThreadStart(ReceiveData));
            thread1.Start();
        }
        delegate void TextBoxCallback(string str);
        public void SetTextBox(string str)
        {
            textBox1.Text = str;

        }
        private int port = 62001;
        private UdpClient udpClient;
        private void ReceiveData()
        {
            //在本机指定的端口接收
            udpClient = new UdpClient(port);
            IPEndPoint remote = null;
            //接收从远程主机发送过来的信息;
            while (true)
            {
                try
                {
                    //关闭udpClient时此句会产生异常
                    byte[] bytes = udpClient.Receive(ref remote);
                    string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
                    TextBoxCallback tx = SetTextBox;
                    this.Dispatcher.Invoke(tx, str);
                }
                catch
                {
                    //退出循环,结束线程
                    break;
                }
                finally
                {
                    udpClient.Close();
                }
            }
        }

        private void sendData()
        {
            UdpClient myUdpClient = new UdpClient();
            IPAddress remoteIP;
            if (IPAddress.TryParse(textBoxRemoteIP.Text, out remoteIP) == false)
            {
                MessageBox.Show("远程IP格式不正确");
                return;
            }
            IPEndPoint iep = new IPEndPoint(remoteIP, port);
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(textBoxSend.Text);
            try
            {
                myUdpClient.Send(bytes, bytes.Length, iep);
                textBoxSend.Clear();
                myUdpClient.Close();
                textBoxSend.Focus();
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, "发送失败");
            }
            finally
            {
                myUdpClient.Close();
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            sendData();
        }
    }
}