歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C#下socket編程:udp協議測試

C#下socket編程:udp協議測試

日期:2017/3/1 10:38:52   编辑:Linux編程

軟件平台:C# + WINCE6.0

硬件平台:tiny6410

界面設計:


設計思路:

1.點擊發送鍵則發送文本

2.開辟一個線程接收網絡數據

注意:

開辟的線程調用主線程的控件會導致不安全,所以用了托管的方式調用


源代碼:

[csharp]

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using System.Net;
  9. using System.Net.Sockets;
  10. using System.Threading;
  11. namespace test_udp
  12. {
  13. public partial class Form1 : Form
  14. {
  15. UdpClient udpclient;
  16. Byte[] sendBytes;
  17. IPEndPoint temp;
  18. public Form1()
  19. {
  20. InitializeComponent();
  21. }
  22. //發送按鍵
  23. private void button1_Click(object sender, EventArgs e)
  24. {
  25. //定義一個字節數組,用來存放發送到遠程主機的信息
  26. sendBytes = Encoding.Default.GetBytes(textBox3.Text);
  27. //調用send方法發送到遠程主機
  28. udpclient.Send(sendBytes, sendBytes.Length);
  29. }
  30. //確認配置
  31. private void button2_Click(object sender, EventArgs e)
  32. {
  33. //實例化udpclient對象
  34. udpclient = new UdpClient(Convert.ToInt32(textBox2.Text));
  35. //調用connect建立默認遠程主機
  36. udpclient.Connect(textBox1.Text, Convert.ToInt32(textBox2.Text));
  37. //實例化ipendpoint對象,用來顯示響應主機的標識
  38. temp = new IPEndPoint(IPAddress.Any,0);
  39. //開啟接收線程
  40. Thread recv_udp = new Thread(new ThreadStart(recv_udp_func));
  41. recv_udp.Start();
  42. }
  43. //接收線程
  44. public void recv_udp_func()
  45. {
  46. while (true)
  47. {
  48. //接收數據包
  49. Byte[] recv_bytes = udpclient.Receive(ref temp);
  50. //將得到的數據包轉換為字符串形式
  51. string return_data = Encoding.Default.GetString(recv_bytes,0,recv_bytes.Length);
  52. //顯示
  53. this.Invoke((EventHandler)delegate { this.textBox4.Text = return_data; });
  54. }
  55. }
  56. }
  57. }
Copyright © Linux教程網 All Rights Reserved