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引用请自己根据缺少的引用进行添加