C#网络编程系列文章(七)之UdpClient实现异步UDP服务器
来源:互联网 发布:淘宝删除我的评价 编辑:程序博客网 时间:2024/06/02 05:31
原创性声明
本文作者:小竹zz 本文地址http://blog.csdn.net/zhujunxxxxx/article/details/44258719 转载请注明出处
文章系列目录
C#网络编程系列文章(一)之Socket实现异步TCP服务器
C#网络编程系列文章(二)之Socket实现同步TCP服务器
C#网络编程系列文章(三)之TcpListener实现异步TCP服务器
C#网络编程系列文章(四)之TcpListener实现同步TCP服务器
C#网络编程系列文章(五)之Socket实现异步UDP服务器
C#网络编程系列文章(六)之Socket实现同步UDP服务器
C#网络编程系列文章(七)之UdpClient实现异步UDP服务器
C#网络编程系列文章(八)之UdpClient实现同步UDP服务器
本文介绍
UdpClient 类在同步阻塞模式中为发送和接收无连接的 UDP 数据包而提供了简单的方法。因为 UDP 是一种无连接的传输协议,所以你不需要在发送和接收数据之前建立任何远程主机连接。你只需要按照下列方式来建立默认的远程主机选项:
使用远程主机名称和端口号作为参数来创建 UdpClient 类的实例。
创建 UdpClient 类的实例然后调用 Connect 方法。
你可以使用任何由 UdpClient 所提供的发送方法把数据发送给远程设备。然后使用 Receive 方法来接收来自于远程主机的数据。
提示:如果你已经指定了一个默认的远程主机,就不要使用主机名称或者 IPEndPoint 来调用 Send 方法。如果你这样做,那么 UdpClient 将会抛出一个异常。
UdpClient 方法同样允许你发送和接收多点传送的数据包。而使用 JoinMulticastGroup 方法可以把 UdpClient 订阅到多点传送分组。也可以使用 DropMulticastGroup 方法把 UdpClient 从多点传送分组的订阅中取消。
本节介绍使用UdpClient实现一个异步的高性能UDP服务器
UdpClient异步UDP服务器
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Net.Sockets;
- using System.Net;
-
- namespace NetFrame.Net.UDP.Listener.Asynchronous
- {
-
-
-
- public class AsyncUDPServer
- {
- #region Fields
-
-
-
- private int _maxClient;
-
-
-
-
-
-
-
-
-
- private UdpClient _server;
-
-
-
-
-
-
- private bool disposed = false;
-
-
-
-
- private byte[] _recvBuffer;
-
- #endregion
-
- #region Properties
-
-
-
-
- public bool IsRunning { get; private set; }
-
-
-
- public IPAddress Address { get; private set; }
-
-
-
- public int Port { get; private set; }
-
-
-
- public Encoding Encoding { get; set; }
-
- #endregion
-
- #region 构造函数
-
-
-
-
-
- public AsyncUDPServer(int listenPort)
- : this(IPAddress.Any, listenPort,1024)
- {
- }
-
-
-
-
-
- public AsyncUDPServer(IPEndPoint localEP)
- : this(localEP.Address, localEP.Port,1024)
- {
- }
-
-
-
-
-
-
-
- public AsyncUDPServer(IPAddress localIPAddress, int listenPort, int maxClient)
- {
- this.Address = localIPAddress;
- this.Port = listenPort;
- this.Encoding = Encoding.Default;
-
- _maxClient = maxClient;
-
- _server = new UdpClient(new IPEndPoint(this.Address, this.Port));
-
- _recvBuffer=new byte[_server.Client.ReceiveBufferSize];
- }
-
- #endregion
-
- #region Method
-
-
-
-
- public void Start()
- {
- if (!IsRunning)
- {
- IsRunning = true;
- _server.EnableBroadcast = true;
- _server.BeginReceive(ReceiveDataAsync, null);
- }
- }
-
-
-
-
- public void Stop()
- {
- if (IsRunning)
- {
- IsRunning = false;
- _server.Close();
-
-
- }
- }
-
-
-
-
-
- private void ReceiveDataAsync(IAsyncResult ar)
- {
- IPEndPoint remote=null;
- byte[] buffer = null;
- try
- {
- buffer = _server.EndReceive(ar, ref remote);
-
-
- RaiseDataReceived(null);
- }
- catch (Exception)
- {
-
- RaiseOtherException(null);
- }
- finally
- {
- if (IsRunning && _server != null)
- _server.BeginReceive(ReceiveDataAsync, null);
- }
- }
-
-
-
-
-
-
- public void Send(string msg, IPEndPoint remote)
- {
- byte[] data = Encoding.Default.GetBytes(msg);
- try
- {
- RaisePrepareSend(null);
- _server.BeginSend(data, data.Length, new AsyncCallback(SendCallback), null);
- }
- catch (Exception)
- {
-
- RaiseOtherException(null);
- }
- }
-
- private void SendCallback(IAsyncResult ar)
- {
- if (ar.IsCompleted)
- {
- try
- {
- _server.EndSend(ar);
-
- RaiseCompletedSend(null);
- }
- catch (Exception)
- {
-
- RaiseOtherException(null);
- }
- }
-
- }
- #endregion
-
- #region 事件
-
-
-
- public event EventHandler<AsyncUDPEventArgs> DataReceived;
-
- private void RaiseDataReceived(AsyncUDPState state)
- {
- if (DataReceived != null)
- {
- DataReceived(this, new AsyncUDPEventArgs(state));
- }
- }
-
-
-
-
- public event EventHandler<AsyncUDPEventArgs> PrepareSend;
-
-
-
-
-
- private void RaisePrepareSend(AsyncUDPState state)
- {
- if (PrepareSend != null)
- {
- PrepareSend(this, new AsyncUDPEventArgs(state));
- }
- }
-
-
-
-
- public event EventHandler<AsyncUDPEventArgs> CompletedSend;
-
-
-
-
-
- private void RaiseCompletedSend(AsyncUDPState state)
- {
- if (CompletedSend != null)
- {
- CompletedSend(this, new AsyncUDPEventArgs(state));
- }
- }
-
-
-
-
- public event EventHandler<AsyncUDPEventArgs> NetError;
-
-
-
-
- private void RaiseNetError(AsyncUDPState state)
- {
- if (NetError != null)
- {
- NetError(this, new AsyncUDPEventArgs(state));
- }
- }
-
-
-
-
- public event EventHandler<AsyncUDPEventArgs> OtherException;
-
-
-
-
- private void RaiseOtherException(AsyncUDPState state, string descrip)
- {
- if (OtherException != null)
- {
- OtherException(this, new AsyncUDPEventArgs(descrip, state));
- }
- }
- private void RaiseOtherException(AsyncUDPState state)
- {
- RaiseOtherException(state, "");
- }
- #endregion
-
- #region Close
-
-
-
-
- public void Close(AsyncUDPState state)
- {
- if (state != null)
- {
-
-
-
- }
- }
-
-
-
- public void CloseAllClient()
- {
-
-
-
-
-
-
- }
-
- #endregion
-
- #region 释放
-
-
-
-
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
-
-
-
-
-
-
-
- protected virtual void Dispose(bool disposing)
- {
- if (!this.disposed)
- {
- if (disposing)
- {
- try
- {
- Stop();
- if (_server != null)
- {
- _server = null;
- }
- }
- catch (SocketException)
- {
-
- RaiseOtherException(null);
- }
- }
- disposed = true;
- }
- }
- #endregion
- }
- }
客户端信息封装了类- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Net.Sockets;
- using System.Net;
-
- namespace NetFrame.Net.UDP.Listener.Asynchronous
- {
- public class AsyncUDPState
- {
-
- public UdpClient udpClient = null;
-
- public const int BufferSize = 1024;
-
- public byte[] buffer = new byte[BufferSize];
-
- public StringBuilder sb = new StringBuilder();
-
- public IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);
- }
- }
服务器事件参数类- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
-
- namespace NetFrame.Net.UDP.Listener.Asynchronous
- {
-
-
-
- public class AsyncUDPEventArgs : EventArgs
- {
-
-
-
- public string _msg;
-
-
-
-
- public AsyncUDPState _state;
-
-
-
-
- public bool IsHandled { get; set; }
-
- public AsyncUDPEventArgs(string msg)
- {
- this._msg = msg;
- IsHandled = false;
- }
- public AsyncUDPEventArgs(AsyncUDPState state)
- {
- this._state = state;
- IsHandled = false;
- }
- public AsyncUDPEventArgs(string msg, AsyncUDPState state)
- {
- this._msg = msg;
- this._state = state;
- IsHandled = false;
- }
- }
- }