- 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; });
- }
- }
- }
- }
复制代码 |