您的位置:首页 > 文旅 > 旅游 > C#udpClient组播

C#udpClient组播

2024/12/23 15:32:36 来源:https://blog.csdn.net/weixin_73535261/article/details/140024257  浏览:    关键词:C#udpClient组播

一、0udpClient

控件:

button(打开,关闭,发送),textbox,richTextBox

打开UDP:

UdpClient udp:

namespace _01udpClient
{public partial class Form1 : Form{public Form1(){InitializeComponent();}//打开UdpClient udp;private void button1_Click(object sender, EventArgs e){//1创建udp对象 指定ip地址和端口号udp = new UdpClient(new IPEndPoint(IPAddress.Any, 8080));//2 接收数据startReceive();}void startReceive(){new Thread(() =>{try{while (true){//创建ip接受客户端的ip地址IPEndPoint ip = null;//接收数据 返回字节数组byte[] body =  udp.Receive(ref ip);string s = Encoding.UTF8.GetString(body);BeginInvoke((Action)(() =>{richTextBox1.AppendText(ip.ToString() + ":" + s + "\t\n");}));}}catch{}}).Start();}//关闭private void button2_Click(object sender, EventArgs e){udp.Close();//关闭udp = null;}private void button3_Click(object sender, EventArgs e){byte[] bs = Encoding.UTF8.GetBytes(this.textBox1.Text);//发数据//参数1 字节数组//参数2 字节长度//参数3 目标主机地址//参数4 端口号udp.Send(bs, bs.Length, "192.168.107.71", 8080);}}
}

二、udpClient组播

namespace _02udpClinet组播
{public partial class Form1 : Form{public Form1(){InitializeComponent();}//打开服务器private void button3_Click(object sender, EventArgs e){udp = new UdpClient(new IPEndPoint(IPAddress.Any, 8080));strartReceive();}UdpClient udp;//异步的方式//1 new Thread() 分线程//2 Task.Run() 异步任务//3 async(异步)和await (等待)async void strartReceive(){while (true){//await 跟一个异步的任务// 等待异步结束之后 再去执行//receiveAsync() 异步接收数据UdpReceiveResult body = await udp.ReceiveAsync();// body.RemoteEndPoint 远程终端//body.Buffer 数据字节数组BeginInvoke((Action)(() =>{richTextBox1.AppendText(body.RemoteEndPoint.ToString() + ":" + Encoding.UTF8.GetString(body.Buffer)+"\t\n");}));}}// 加入组播private void button1_Click(object sender, EventArgs e){//Join 加入udp.JoinMulticastGroup(IPAddress.Parse(this.textBox1.Text));//加入组播地址}private void button2_Click(object sender, EventArgs e){//发送消息byte[] bs =  Encoding.UTF8.GetBytes(this.textBox2.Text);udp.Send(bs, bs.Length, this.textBox1.Text, 8080);}}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com