UDP通信学习
学习了很久写一个UDP通信学习的例子
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Threading; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public delegate void back(string str); UdpClient udp_server, udp_client; bool server_zt; public Form1() { InitializeComponent(); } public void add() { try { IPEndPoint ipinfo = new IPEndPoint(IPAddress.Any, 1000); IPEndPoint ipfo = new IPEndPoint(IPAddress.Any, 0); udp_client = new UdpClient(ipinfo); Byte[] sendstr; while (server_zt) { sendstr = udp_client.Receive(ref ipfo); textadd(Encoding.Default.GetString(sendstr)); } } catch(Exception err) { MessageBox.Show(err.Message,"错误!",MessageBoxButtons.OK,MessageBoxIcon.Error); } } public void textadd(string str) { if (listBox1.InvokeRequired) { back s = new back(textadd); listBox1.Invoke(s, str); } else { listBox1.Items.Add(str + "[" + DateTime.Now + "]"); listBox1.SelectedIndex = listBox1.Items.Count - 1; } } private void Form1_Load(object sender, EventArgs e) { server_zt = true; Thread t = new Thread(new ThreadStart(add)); t.Start(); } private void button2_Click(object sender, EventArgs e) { try { if (comboBox1.Text.Length > 0) { udp_server = new UdpClient(); Byte[] s_send = Encoding.Default.GetBytes(comboBox1.Text); udp_server.Send(s_send, s_send.Length, "localhost", 1000); comboBox1.Text = ""; } else { MessageBox.Show("发表内容不能为空!", "提示!",MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } } catch(Exception err) { MessageBox.Show(err.Message,"错误!",MessageBoxButtons.OK,MessageBoxIcon.Error); } } } }
运行界面