using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Net.Sockets; using System.Net; using System.Threading; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); IPAddress[] ips = Dns.GetHostAddresses(""); this.textBox1.Text = ips[0].ToString(); this.textBox4.Text = ips[0].ToString(); } private void textBox1_TextChanged(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { Control.CheckForIllegalCrossThreadCalls = false; } Socket mySocket; IPEndPoint Remoteendpoint; EndPoint RemotePoint; private void button1_Click(object sender, EventArgs e) { mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //服务器 IPAddress ipadd = IPAddress.Parse(this.textBox1.Text); IPEndPoint ipend = new IPEndPoint(ipadd, int.Parse(this.textBox2.Text)); mySocket.Bind(ipend); //客户机 IPAddress ipRemote = IPAddress.Parse(this.textBox4.Text); Remoteendpoint = new IPEndPoint(ipadd, int.Parse(this.textBox3.Text)); RemotePoint=(EndPoint)Remoteendpoint; //使用线程处理数据接收 Thread thread = new Thread(new ThreadStart(Receive)); thread.IsBackground = true; thread.Start(); } public delegate void MyInvoke(string strRecv) ; void Receive() { //接受数据处理线程 string msg; byte[] data = new byte[1024]; MyInvoke myI = new MyInvoke(ShowMsg); while (true) { if (mySocket==null||mySocket.Available<1) { Thread.Sleep(200); continue; } //跨线程调用控件 //接受udp数据报,引用参数RemotePoint获得源地址 int rlen = mySocket.ReceiveFrom(data, ref RemotePoint); msg = Encoding.Default.GetString(data, 0, rlen); this.textBox5.BeginInvoke(myI, new object[] { RemotePoint.ToString() + ":" + msg }); } } void ShowMsg(string msg) { //接受数据显示 this.textBox5.AppendText(msg+" "); } private void button2_Click(object sender, EventArgs e) { string msg; msg=this.textBox6.Text; byte [] data= Encoding.Default.GetBytes(msg); mySocket.SendTo(data,data.Length,SocketFlags.None,RemotePoint); } } }