軟件平台:C# + WINCE6.0
硬件平台:tiny6410
界面設計:
設計思路:
1.點擊發送鍵則發送文本
2.開辟一個線程接收網絡數據
注意:
開辟的線程調用主線程的控件會導致不安全,所以用了托管的方式調用
源代碼:
[csharp]
- 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; });
- }
- }
- }
- }