接收端
using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Windows.Forms; namespace UDPReceiveTest { public partial class Form1 : Form { public UdpClient udpClient; public Thread UdpThread; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { if (UdpThread != null) { UdpThread.Abort(); Thread.Sleep(TimeSpan.FromMilliseconds(500d)); } System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false; if (udpClient != null) { UdpThread.Abort(); Thread.Sleep(TimeSpan.FromMilliseconds(500d)); udpClient.Close(); } try { udpClient = new UdpClient(int.Parse(txtPort.Text)); UdpThread = new Thread(new ThreadStart(UdpReciveThread)); UdpThread.Start(); } catch (Exception y) { MessageBox.Show(this, y.Message, "Error", MessageBoxButtons.OK,MessageBoxIcon.Error); this.Dispose(true); } } private void button1_Click(object sender, EventArgs e) { txtMessage.Text = string.Empty; } delegate void SetTextCallback(IPEndPoint remoteHost, byte[] buf, string bufs); //接收数据线程 void UdpReciveThread() { IPHostEntry oIPHost = Dns.GetHostEntry(Environment.MachineName); IPEndPoint remoteHost = new IPEndPoint(IPAddress.Any, ); while (udpClient != null &&Thread.CurrentThread.ThreadState.Equals(ThreadState.Running)) { try { byte[] buf = udpClient.Receive(ref remoteHost); string bufs = Encoding.UTF8.GetString(buf); txtMessage.Text += remoteHost.Address.ToString() + "说:" +Environment.NewLine; txtMessage.Text += bufs + Environment.NewLine; } catch (Exception y) { } } txtMessage.Text += "结束..." + (char); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { try { udpClient.Close(); UdpThread.Abort(); } catch { } } } }
发送端
using System; using System.Net.Sockets; using System.Text; using System.Windows.Forms; namespace UDPSendTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnSend_Click(object sender, EventArgs e) { try { UdpClient uc = new UdpClient(txtIP.Text, int.Parse(txtPort.Text)); byte[] sendbuf = Encoding.UTF8.GetBytes(txtMessage.Text); uc.Send(sendbuf, sendbuf.Length); } catch (Exception y) { MessageBox.Show(this, y.Message, "发送失败", MessageBoxButtons.OK,MessageBoxIcon.Hand); } } } }