接收端:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; namespace Server { class Program { static void Main(string[] args) { var udpReceiver = new UdpClient(8112, AddressFamily.InterNetwork); IPEndPoint remoteHost = null; var data = udpReceiver.Receive(ref remoteHost); var msg = Encoding.Default.GetString(data); Console.WriteLine(msg); Console.In.ReadLine(); } } }
发送端:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Net; namespace Client { class Program { static void Main(string[] args) { var msg = Console.In.ReadLine(); var udpClient = new UdpClient(8110); var udpRemote = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8112); var data = Encoding.Default.GetBytes(msg); udpClient.Send(data,data.Length,udpRemote); } } }