欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > UdpClient

UdpClient

2025/3/16 3:48:20 来源:https://blog.csdn.net/zoushier/article/details/146256160  浏览:    关键词:UdpClient

Socket实现Udp的发送和接收

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace _1Socket实现udp的发送
{public partial class Form1 : Form{public Form1(){InitializeComponent();}Socket soc;//打开private void button1_Click(object sender, EventArgs e){soc = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);soc.Bind(new IPEndPoint(IPAddress.Parse("192.168.107.14"), 3030));Task.Run(() =>{while (true){byte[] buffer = new byte[1024];EndPoint ip = new IPEndPoint(IPAddress.None, 0);// 初始化远程终端,没ip ,没端口soc.ReceiveFrom(buffer, 0, ref ip); //接收了消息,获取远程终端IPEndPoint ip1 = ip as IPEndPoint; //EndPoint的ip类型 转成IPEndPoint类型BeginInvoke( new Action(() =>{richTextBox1.AppendText($"接收到了来自{ip1.ToString()}的消息:{Encoding.UTF8.GetString(buffer)}\r\n");}));}});}//关闭private void button2_Click(object sender, EventArgs e){soc.Close();}//发送private void button3_Click(object sender, EventArgs e){soc.SendTo(Encoding.UTF8.GetBytes("9福星还有一个大铲子输了"), new IPEndPoint(IPAddress.Parse("192.168.107.46"), 3000));}private void richTextBox1_TextChanged(object sender, EventArgs e){}}
}

 

UdpClient

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace _2UDPClient
{public partial class Form1 : Form{public Form1(){InitializeComponent();}UdpClient udp;private void button1_Click(object sender, EventArgs e){udp = new UdpClient(new IPEndPoint(IPAddress.Parse("192.168.107.14"), 3000));Task.Run(() =>{try{while (true){IPEndPoint ip = null;byte[] bs = udp.Receive(ref ip);//接收数据 传递远程终端string s = Encoding.UTF8.GetString(bs);BeginInvoke(new Action(() =>{richTextBox1.AppendText(ip.ToString() + ":" + s + "\r\n");}));}}catch (Exception ex){MessageBox.Show("UDP已经关闭");}});}private void button2_Click(object sender, EventArgs e){udp.Close();}private void button3_Click(object sender, EventArgs e){byte[] bs = Encoding.UTF8.GetBytes("今天又周五了,明天可以休息了");udp.Send(bs,bs.Length,"192.168.107.210",8000);}}
}

 

版权声明:

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

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

热搜词