下面是比较早期写的一个监控UDP接收的线例子:
1 //申明委托
2 public delegate void mydelegate();
3 //添加调用控制的方法
4 public void outtext()
5 {
6 textBox1.Text = Read_str;
7
8 }
9 public void start_server()
10 {
11 while (true)
12 {
13 //接收从远程主机发送到本地8090端口的数据
14 byte[] recData = server.Receive(ref receivePoint);
15 ASCIIEncoding encode = new ASCIIEncoding();
16 //获得客户端请求数据
17 Read_str = encode.GetString(recData);
18 //提取客户端的信息,存放到定义为temp的字符串数组中
19 //string[] temp = Read_str.Split("/".ToCharArray());
20 //在线程中调用对象;
21 mydelegate mydelegate = new mydelegate( outtext );
22 //BeginInvoke/invoke(同步或异步) 方法来将调用封送到适当的线程
23 textBox1.BeginInvoke(mydelegate, new object[] { });
24
25 }
26 }
27 public void run()
28 {
29 //利用本地8080端口号来初始化一个UDP网络服务
30 server = new UdpClient(port);
31 receivePoint = new IPEndPoint(new IPAddress(ip), port);
32 //开一个线程
33 startServer = new Thread(new ThreadStart(start_server));
34 //启动线程
35 startServer.Start();
36
37 }
38 private void Form1_Load(object sender, EventArgs e)
39 {
40 //启动对时服务
41 run();
42
43 }
2 public delegate void mydelegate();
3 //添加调用控制的方法
4 public void outtext()
5 {
6 textBox1.Text = Read_str;
7
8 }
9 public void start_server()
10 {
11 while (true)
12 {
13 //接收从远程主机发送到本地8090端口的数据
14 byte[] recData = server.Receive(ref receivePoint);
15 ASCIIEncoding encode = new ASCIIEncoding();
16 //获得客户端请求数据
17 Read_str = encode.GetString(recData);
18 //提取客户端的信息,存放到定义为temp的字符串数组中
19 //string[] temp = Read_str.Split("/".ToCharArray());
20 //在线程中调用对象;
21 mydelegate mydelegate = new mydelegate( outtext );
22 //BeginInvoke/invoke(同步或异步) 方法来将调用封送到适当的线程
23 textBox1.BeginInvoke(mydelegate, new object[] { });
24
25 }
26 }
27 public void run()
28 {
29 //利用本地8080端口号来初始化一个UDP网络服务
30 server = new UdpClient(port);
31 receivePoint = new IPEndPoint(new IPAddress(ip), port);
32 //开一个线程
33 startServer = new Thread(new ThreadStart(start_server));
34 //启动线程
35 startServer.Start();
36
37 }
38 private void Form1_Load(object sender, EventArgs e)
39 {
40 //启动对时服务
41 run();
42
43 }
参考文章: