基于UDP、TCP协议的C#网络编程之一
基于UDP、TCP协议的C#网络编程之一
|
public partial class Form1 : Form { UdpClient uc; //声明UDPClient public Form1() { uc = new UdpClient(); //初始化 InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string temp = this.textBox1.Text; //保存TextBox文本 //将该文本转化为字节数组 byte[] b = System.Text.Encoding.UTF8.GetBytes(temp); //向本机的8888端口发送数据 uc.Send(b, b.Length,Dns.GetHostName(),8888); } } |
|
public partial class Form2 : Form { UdpClient uc = null; //声明UDPClient public Form1() { //屏蔽跨线程改控件属性那个异常 CheckForIllegalCrossThreadCalls = false; InitializeComponent(); //注意此处端口号要与发送方相同 uc = new UdpClient(8888); //开一线程 Thread th = new Thread(new ThreadStart(listen)); //设置为后台 th.IsBackground = true; th.Start(); } private void listen() { //声明终结点 IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.0.10"),8888); while (true) { //获得Form1发送过来的数据包 string text = System.Text.Encoding.UTF8.GetString(uc.Receive(ref iep)); //加入ListBox this.listBox1.Items.Add(text); } } } |
|
uc = new UdpClient();
uc.Connect(IPAddress.Parse("192.168.0.10"), 8888);
.....
uc.Send(b, b.Length);
|
|
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.0.10"),8888); ......... string text = System.Text.Encoding.UTF8.GetString(uc.Receive(ref iep)); |
网上对这个貌似还是有点误解,很多人说,这里的IPEndPoint的端口号如果随便指定,也可以收到发送过来的消息,但是就是不知道为什么,我写的更简单:
|
IPEndPoint iep = null; ......... string text = System.Text.Encoding.UTF8.GetString(uc.Receive(ref iep)); |
看出问题来了吧,关键是uc.Receive方法里的ref参数,ref关键字使参数按引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。所以你只要扔给它一个值就得了,管他什么端口号,况且端口早在声明UdpClient的时候就指定好了。
有点长,分两截。
浙公网安备 33010602011771号