C#教程之C#中使用UDP通讯实例

若是须要查看更多文章,请微信搜索公众号 csharp编程大全,须要进C#交流群群请加微信z438679770,备注进群, 我邀请你进群! ! !编程

网络通讯协议中的UDP通讯是无链接通讯,客户端在发送数据前无需与服务器端创建链接,即便服务器端不在线也能够发送,可是不能保证服务器端能够收到数据。本文实例即为基于C#实现的UDP通讯。具体功能代码以下:数组

服务器端代码以下服务器

static void Main(string[] args)
{
  UdpClient client = null;
  string receiveString = null;
  byte[] receiveData = null;
  //实例化一个远程端点,IP和端口能够随意指定,等调用client.Receive(ref remotePoint)时会将该端点改为真正发送端端点
  IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);
 
  while (true)
  {
 client = new UdpClient(11000);
 receiveData = client.Receive(ref remotePoint);//接收数据
 receiveString = Encoding.Default.GetString(receiveData);
 Console.WriteLine(receiveString);
 client.Close();//关闭链接
  }
}
客户端代码以下:

static void Main(string[] args)
{
  string sendString = null;//要发送的字符串
  byte[] sendData = null;//要发送的字节数组
  UdpClient client = null;
 
  IPAddress remoteIP = IPAddress.Parse("127.0.0.1");
  int remotePort = 11000;
  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();//关闭链接
  }