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

本文实例讲述了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#程序设计有所帮助。

(0)

相关推荐

  • C#中使用UDP通信实例

    网络通信协议中的UDP通信是无连接通信,客户端在发送数据前无需与服务器端建立连接,即使服务器端不在线也可以发送,但是不能保证服务器端可以收到数据.本文实例即为基于C#实现的UDP通信.具体功能代码如下: 服务器端代码如下: static void Main(string[] args) { UdpClient client = null; string receiveString = null; byte[] receiveData = null; //实例化一个远程端点,IP和端口可以随意指定

  • C#实现简易的加密、解密字符串工具类实例

    本文实例讲述了C#实现简易的加密.解密字符串工具类.分享给大家供大家参考.具体如下: 这里的类CypherHelper是一个用于加密.解密字符串的工具类~~~,适合于方便地加密.解密长度较短的密码等字符串(C#里面已经有了库System.Security.Cryptography,对于比较长的字符串或流来说是一个更好的选择) 类CypherHelper代码: class CypherHelper { /// <summary> /// 加密字符串 /// </summary> //

  • 使用C#实现基于TCP和UDP协议的网络通信程序的基本示例

    C#中使用TCP通信 TCP通信需要通信双方都在线,所以需要先启动服务端进行监听,客户端才能获得连接,服务端代码: static void Main(string[] args) { TcpClient client = null; NetworkStream stream = null; byte[] buffer = null; string receiveString = null; IPAddress localIP = IPAddress.Parse("127.0.0.1")

  • C#基于UDP实现的P2P语音聊天工具

    语音获取 要想发送语音信息,首先得获取语音,这里有几种方法,一种是使用DirectX的DirectXsound来录音,我为了简便使用一个开源的插件NAudio来实现语音录取. 在项目中引用NAudio.dll //------------------录音相关----------------------------- private IWaveIn waveIn; private WaveFileWriter writer; private void LoadWasapiDevicesCombo(

  • C#实现简单的Http请求实例

    本文实例讲述了C#实现简单的Http请求的方法.分享给大家供大家参考.具体分析如下: 通过.Net中的两个类HttpWebRequest类,HttpWebResponse类来实现Http的请求,响应处理. 第一个小测试是请求百度首页(http://www.baidu.com)的内容,也就是要获得百度首页的html内容, 实现步骤: 1.通过WebRequest类创建一个HttpWebRequest的对象,该对象可以包含Http请求信息. (这里有点供大家思考:为什么要通过父类WebRequest

  • C#实现的UDP收发请求工具类实例

    本文实例讲述了C#实现的UDP收发请求工具类.分享给大家供大家参考,具体如下: 初始化: ListeningPort = int.Parse(ConfigurationManager.AppSettings["ListeningPort"]); SendingPort = int.Parse(ConfigurationManager.AppSettings["SendingPort"]); SendingIp = ConfigurationManager.AppSe

  • C#实现支持断点续传多线程下载客户端工具类

    复制代码 代码如下: /* .Net/C#: 实现支持断点续传多线程下载的 Http Web 客户端工具类 (C# DIY HttpWebClient) * Reflector 了一下 System.Net.WebClient ,改写或增加了若干: * DownLoad.Upload 相关方法! * DownLoad 相关改动较大! * 增加了 DataReceive.ExceptionOccurrs 事件! * 了解服务器端与客户端交互的 HTTP 协议参阅: * 使文件下载的自定义连接支持

  • C#的Socket实现UDP协议通信示例代码

    今天稍花化了一点时间,利用C#的Socket验证了UDP的通信,为接下来特地利用UDP做个分布式的通信仿真系统打下基础.众所周知,UDP 就是用户数据报协议,在互联网参考模型的第四层--传输层.与TCP协议同层,都是提供信息的传输服务,但与TCP最大区别就是,它是一种无连接不可靠的信息传输. 什么是无连接不可靠?直白点讲就是,发送数据的时候,直接把UDP包往网络一扔就完事了,接不接受收到发送的就不理了:接受数据的时候,有发给本地的UDP包就照单全收,收完再看是谁发的.相比TCP,少了握手建立连接

  • c#实现简单控制台udp异步通信程序示例

    实现客户端发送请求,服务器端响应机制 UDP客户端代码 复制代码 代码如下: using System;using System.Text;using System.Net;using System.Net.Sockets; namespace Client{    class Program    {        //客户端 Socket对象        private static Socket clientSocket;        //服务器端 终点        private

  • 基于C#的UDP协议的同步通信实现代码

    一.摘要 总结基于C#的UDP协议的同步通信.  二.实验平台 Visual Studio 2010  三.实验原理 UDP传输协议同TCP传输协议的区别可查阅相关文档,此处不再赘述. 四.实例 4.1 采用socket实现UDP 由于UDP是一种无连接的协议.因此,为了使服务器应用能够发送和接收UDP数据包,则需要做两件事情: (1) 创建一个Socket对象: (2) 将创建的套接字对象与本地IPEndPoint进行绑定. 完成上述步骤后,那么创建的套接字就能够在IPEndPoint上接收流

  • C#模拟http 发送post或get请求的简单实例

    private string HttpPost(string Url, string postDataStr) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = Enco

  • C#获取Windows进程监听的TCP/UDP端口实例

    1.在Windows下用CMD netstat命令可以获得当前进程监听端口号的信息,如netstat -ano可以看到IP.port.状态和监听的PID.那么可以执行CMD这个进程得到监听的端口号信息,C#代码如下: 复制代码 代码如下: //进程id int pid = ProcInfo.ProcessID; //存放进程使用的端口号链表 List<int> ports = new List<int>(); Process pro = new Process(); pro.Sta

随机推荐