码迷,mamicode.com
首页 > 其他好文 > 详细

UDP中接收和发送数据

时间:2019-11-04 13:34:32      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:point   res   字节数组   name   bytes   read   字节   ring   remote   

/// <summary>
///A程序发送数据
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
string sendString = null;//要发送的字符串
byte[] sendData = null;//要发送的字节数组
UdpClient client = null;

IPAddress remoteIP = IPAddress.Parse("192.168.1.100"); //假设发送给这个IP
int remotePort = 8021;///端口号
IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);//实例化一个远程端点

while (true)
{
sendString = Console.ReadLine();
sendData = Encoding.Default.GetBytes(sendString);

client = new UdpClient();
client.Send(sendData, sendData.Length, remotePoint);//将数据发送到远程端点
client.Close();//关闭连接
}
}

 

/// <summary>
/// B程序接收数据
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
UdpClient client = null;
string receiveString = null;
byte[] receiveData = null;
///这里是不需要知道发送者的IP,只需要端口号,因为这里是接收
IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);

while (true)
{
client = new UdpClient(2003);
receiveData = client.Receive(ref remotePoint);//接收数据
receiveString = Encoding.Default.GetString(receiveData);
Console.WriteLine(receiveString);
client.Close();//关闭连接
}
}

 

UDP中接收和发送数据

标签:point   res   字节数组   name   bytes   read   字节   ring   remote   

原文地址:https://www.cnblogs.com/yjm8023/p/11791393.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!