C#基于UDP进行异步通信的方法

所属分类: 软件编程 / C#教程 阅读数: 70
收藏 0 赞 0 分享

本文实例讲述了C#基于UDP进行异步通信的方法。分享给大家供大家参考。具体如下:

服务器端:

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace AsyncServer
{
 public class UdpState
 {
  public UdpClient udpClient;
  public IPEndPoint ipEndPoint;
  public const int BufferSize = 1024;
  public byte[] buffer = new byte[BufferSize];
  public int counter = 0;
 }
 public class AsyncUdpSever
 {
  private IPEndPoint ipEndPoint = null;
  private IPEndPoint remoteEP = null;
  private UdpClient udpReceive = null;
  private UdpClient udpSend = null;
  private const int listenPort = 1100;
  private const int remotePort = 1101;
  UdpState udpReceiveState = null;
  UdpState udpSendState = null;
  private ManualResetEvent sendDone = new ManualResetEvent(false);
  private ManualResetEvent receiveDone = new ManualResetEvent(false);
  public AsyncUdpSever()
  {
   ipEndPoint = new IPEndPoint(IPAddress.Any, listenPort);
   remoteEP = new IPEndPoint(Dns.GetHostAddresses(Dns.GetHostName())[0], remotePort);
   udpReceive = new UdpClient(ipEndPoint);
   udpSend = new UdpClient();
   udpReceiveState = new UdpState();   
   udpReceiveState.udpClient = udpReceive;
   udpReceiveState.ipEndPoint = ipEndPoint;
   udpSendState = new UdpState();
   udpSendState.udpClient = udpSend;
   udpSendState.ipEndPoint = remoteEP;
  }
  public void ReceiveMsg()
  {
   Console.WriteLine("listening for messages");
   while(true)
   {
    lock (this)
    { 
     IAsyncResult iar = udpReceive.BeginReceive(new AsyncCallback(ReceiveCallback), udpReceiveState);
     receiveDone.WaitOne();
     Thread.Sleep(100);
    }
   }
  }
  private void ReceiveCallback(IAsyncResult iar)
  {
   UdpState udpReceiveState = iar.AsyncState as UdpState;
   if (iar.IsCompleted)
   {
    Byte[] receiveBytes = udpReceiveState.udpClient.EndReceive(iar, ref udpReceiveState.ipEndPoint);
    string receiveString = Encoding.ASCII.GetString(receiveBytes);
    Console.WriteLine("Received: {0}", receiveString);
    //Thread.Sleep(100);
    receiveDone.Set();
    SendMsg();
   }
  }
  private void SendMsg()
  {
   udpSend.Connect(udpSendState.ipEndPoint);
   udpSendState.udpClient = udpSend;
   udpSendState.counter ++;
   string message = string.Format("第{0}个UDP请求处理完成!",udpSendState.counter);
   Byte[] sendBytes = Encoding.Unicode.GetBytes(message);
   udpSend.BeginSend(sendBytes, sendBytes.Length, new AsyncCallback(SendCallback), udpSendState);
   sendDone.WaitOne();
  }
  private void SendCallback(IAsyncResult iar)
  {
   UdpState udpState = iar.AsyncState as UdpState;
   Console.WriteLine("第{0}个请求处理完毕!", udpState.counter);
   Console.WriteLine("number of bytes sent: {0}", udpState.udpClient.EndSend(iar));
   sendDone.Set();
  }
  public static void Main()
  {
   AsyncUdpSever aus = new AsyncUdpSever();
   Thread t = new Thread(new ThreadStart(aus.ReceiveMsg));
   t.Start();
   Console.Read();
  }
 }
}

客户端:

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace AsyncClient
{
 public class UdpState
 {
  public UdpClient udpClient = null;
  public IPEndPoint ipEndPoint = null;
  public const int BufferSize = 1024;
  public byte[] buffer = new byte[BufferSize];
  public int counter = 0;
 }
 public class AsyncUdpClient
 {
  public static bool messageSent = false;
  // Receive a message and write it to the console.
  private const int listenPort = 1101;
  private const int remotePort = 1100;
  private IPEndPoint localEP = null;
  private IPEndPoint remoteEP = null;
  private UdpClient udpReceive = null;
  private UdpClient udpSend = null;
  private UdpState udpSendState = null;
  private UdpState udpReceiveState = null;
  private int counter = 0;
  private ManualResetEvent sendDone = new ManualResetEvent(false);
  private ManualResetEvent receiveDone = new ManualResetEvent(false);
  private Socket receiveSocket;
  private Socket sendSocket;
  public AsyncUdpClient()
  {
   localEP = new IPEndPoint(IPAddress.Any, listenPort);
   remoteEP = new IPEndPoint(Dns.GetHostAddresses(Dns.GetHostName())[0],remotePort);
   udpReceive = new UdpClient(localEP);   
   udpSend = new UdpClient();
   udpSendState = new UdpState();
   udpSendState.ipEndPoint = remoteEP;
   udpSendState.udpClient = udpSend;
   udpReceiveState = new UdpState();
   udpReceiveState.ipEndPoint = remoteEP;
   udpReceiveState.udpClient = udpReceive;
   receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
   receiveSocket.Bind(localEP);
   sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
   sendSocket.Bind(remoteEP);
  }
  public void SendMsg()
  { 
   udpSend.Connect(remoteEP);
   //Thread t = new Thread(new ThreadStart(ReceiveMessages));
   //t.Start();
   Byte[] sendBytes;
   string message;   
   while (true)
   { 
    message = "Client" + (counter++).ToString();
    lock (this)
    {
     sendBytes = Encoding.ASCII.GetBytes(message);
     udpSendState.counter = counter;
     udpSend.BeginSend(sendBytes, sendBytes.Length, new AsyncCallback(SendCallback), udpSendState);
     sendDone.WaitOne();
     Thread.Sleep(200);
     ReceiveMessages();
    }
   }    
  }
  public void SendCallback(IAsyncResult iar)
  {
   UdpState udpState = iar.AsyncState as UdpState;
   if (iar.IsCompleted)
   {
    Console.WriteLine("第{0}个发送完毕!", udpState.counter);
    Console.WriteLine("number of bytes sent: {0}", udpState.udpClient.EndSend(iar));
    //if (udpState.counter == 10)
    //{
    // udpState.udpClient.Close();
    //}
    sendDone.Set();
   }   
  }
  public void ReceiveMessages()
  {
   lock (this)
   {
    udpReceive.BeginReceive(new AsyncCallback(ReceiveCallback), udpReceiveState);
    receiveDone.WaitOne();
    Thread.Sleep(100);
   } 
  }
  public void ReceiveCallback(IAsyncResult iar)
  {
   UdpState udpState = iar.AsyncState as UdpState;
   if (iar.IsCompleted)
   {
    Byte[] receiveBytes = udpState.udpClient.EndReceive(iar, ref udpReceiveState.ipEndPoint);
    string receiveString = Encoding.Unicode.GetString(receiveBytes);
    Console.WriteLine("Received: {0}", receiveString);
    receiveDone.Set();
   }   
  }
  public static void Main()
  {
   AsyncUdpClient auc = new AsyncUdpClient();
   auc.SendMsg();
   Console.Read();
  }
 }
}

希望本文所述对大家的C#程序设计有所帮助。

更多精彩内容其他人还在看

C#抽象类与抽象方法详解

这篇文章主要为大家详细介绍了C#抽象类与抽象方法的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

C#代码实现扑克牌排序的几种方式

今天小编就为大家分享一篇关于C#代码实现扑克牌排序,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
收藏 0 赞 0 分享

C#泛型概念的简介与泛型的使用

今天小编就为大家分享一篇关于C#泛型概念的简介与泛型的使用,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
收藏 0 赞 0 分享

C# 7.0 使用下划线忽略使用的变量的原因分析

这篇文章主要介绍了C# 7.0 使用下划线忽略使用的变量的原因浅析,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

C# 中使用正则表达式匹配字符的含义

正则表达式的作用用来描述字符串的特征。本文重点给大家介绍C# 中使用正则表达式匹配字符的含义,非常不错,具有一定的参考借鉴价值,需要的朋友参考下吧
收藏 0 赞 0 分享

C# Dictionary和SortedDictionary的简介

今天小编就为大家分享一篇关于C# Dictionary和SortedDictionary的简介,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
收藏 0 赞 0 分享

C#中SQL Command的基本用法

今天小编就为大家分享一篇关于C#中SQL Command的基本用法,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
收藏 0 赞 0 分享

C#使用SQL DataReader访问数据的优点和实例

今天小编就为大家分享一篇关于C#使用SQL DataReader访问数据的优点和实例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
收藏 0 赞 0 分享

C#使用SQL Dataset数据集代码实例

今天小编就为大家分享一篇关于的文章,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
收藏 0 赞 0 分享

C#使用SQL DataAdapter数据适配代码实例

今天小编就为大家分享一篇关于C#使用SQL DataAdapter数据适配代码实例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
收藏 0 赞 0 分享
查看更多