本文博客链接:http://blog.csdn.net/jdh99,作者:jdh,转载请注明.
软件平台:C# + WINCE6.0
硬件平台:tiny6410
界面设计:
设计思路:
1.点击发送键则发送文本
2.开辟一个线程接收网络数据
注意:
开辟的线程调用主线程的控件会导致不安全,所以用了托管的方式调用
源代码:
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 test_udp { public partial class Form1 : Form { UdpClient udpclient; Byte[] sendBytes; IPEndPoint temp; public Form1() { InitializeComponent(); } //发送按键 private void button1_Click(object sender, EventArgs e) { //定义一个字节数组,用来存放发送到远程主机的信息 sendBytes = Encoding.Default.GetBytes(textBox3.Text); //调用send方法发送到远程主机 udpclient.Send(sendBytes, sendBytes.Length); } //确认配置 private void button2_Click(object sender, EventArgs e) { //实例化udpclient对象 udpclient = new UdpClient(Convert.ToInt32(textBox2.Text)); //调用connect建立默认远程主机 udpclient.Connect(textBox1.Text, Convert.ToInt32(textBox2.Text)); //实例化ipendpoint对象,用来显示响应主机的标识 temp = new IPEndPoint(IPAddress.Any,0); //开启接收线程 Thread recv_udp = new Thread(new ThreadStart(recv_udp_func)); recv_udp.Start(); } //接收线程 public void recv_udp_func() { while (true) { //接收数据包 Byte[] recv_bytes = udpclient.Receive(ref temp); //将得到的数据包转换为字符串形式 string return_data = Encoding.Default.GetString(recv_bytes,0,recv_bytes.Length); //显示 this.Invoke((EventHandler)delegate { this.textBox4.Text = return_data; }); } } } }