wpf udp一个界面的发送接收

 

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

 

 

 public partial class MainWindow : Window//你自己创建wpf界面的名字

    {

 

public MainWindow()//你自己创建wpf界面的名字
        {
            InitializeComponent();

            send("192.168.1.111",55555,"asdf");

            receive();

        }

   //实例化udp网络发送
        UdpClient udpcSend = new UdpClient();
        /// <summary>
        /// udp发送
        /// </summary>
        /// <param name="ip">远端IP地址</param>
        /// <param name="port">远端端口</param>
        /// <param name="data">数据</param>
        public void send(string ip, int port, string data)
        {
            try
            {
                byte[] byteArray = System.Text.Encoding.Default.GetBytes(data);
                IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Parse(ip), port);//发送到的端口号以及IP地址
                udpcSend.Send(byteArray, byteArray.Length, remoteIpep);//发送
            }
            catch (Exception ex)
            {
                log.Info(ex);
            }

        }

public static Thread thread = null;

public  void receive()

{

thread = new Thread(ReceiveMessage);

thread.Start();

thread.IsBackground = true;

}

 

  public void ReceiveMessage(object obj)
        {//udpcSend = new UdpClient(本机的udp端口);
            udpServer = new Socket
                (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //2.Bind ip and port
            udpServer.Bind(new IPEndPoint(IPAddress.Parse(locip), locport));
            //与上方new的本机udp端口
            while (true)
            {
                try
                {

                    EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    byte[] data = new byte[10000];
                    int length = udpServer.ReceiveFrom(data, ref remoteEndPoint);//此方法把数据来源ip、port放到第二个参数中
                    string message = Encoding.UTF8.GetString(data, 0, length);
                    if (message != null)
                    {
                    Console.Write(message);
                    }

                }

                catch (Exception ex)
                {
                    log.Info(ex);
                    break;
                }

            }
        }

        }
        

}

这样一个简单的收发就结束了,如果本代码缺少using引用请自己根据缺少的引用进行添加

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值