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; using System.Net.Sockets; using System.Threading; namespace SocketApp { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false; } /// <summary> /// 发送 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { UdpClient sendup = new UdpClient(); IPAddress ipremto; try { ipremto = IPAddress.Parse(textBox1.Text); } catch { MessageBox.Show("ip错误", "Error"); return; } IPEndPoint ipep = new IPEndPoint(ipremto, 1868); Byte[] b = null; Encoding enc = Encoding.ASCII; string str = textBox2.Text; b = enc.GetBytes(str.ToCharArray()); sendup.Send(b, b.Length, ipep); textBox2.Clear(); sendup.Close(); } private void button1_Click(object sender, EventArgs e) { //创建一个线程 th = new Thread(new ThreadStart(Read)); //启动线程 th.Start(); } private UdpClient uc; private Thread th; private IPEndPoint ipre; private bool ReadFlag = true; /// <summary> /// 接收监听 /// </summary> private void Read() { uc = new UdpClient(1858); ipre = null; Encoding enc = Encoding.ASCII; while (ReadFlag == true) { Byte[] data = uc.Receive(ref ipre); String strdata = enc.GetString(data); string reip = ipre.Address.ToString(); listBox1.Items.Add(reip + ":" + strdata); } } private void button3_Click(object sender, EventArgs e) { this.listBox1.Items.Clear(); } } }