C# Udp 服务器异步模型

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace AsyncUdpSever
{
    public class UdpServer
    {
        private int _udpPort;

        private Socket _udpSocket;

        public UdpServer(int port)
        {
            this._udpPort = port;
            Console.WriteLine("Server Start...@" + port.ToString());
        }

        /// <summary>
        /// ysl 线程处理
        /// </summary>
        public void Start()
        {
            //本地IP与指定端口
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, _udpPort);

            //服务器Udp Socket
            _udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _udpSocket.Bind(ipep);

            //异步接收
            AsyncBeginReceive();
        }

        protected void Stop()
        {
            try
            {
                _udpSocket.Close();
                Thread.Sleep(100);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private void AsyncBeginReceive()
        {
            while (true)
            {
                try
                {
                    UdpState state = new UdpState();

                    state._receiveDone.Reset();

                    _udpSocket.BeginReceiveFrom(
                        state._data,
                        0,
                        UdpState._bufferSize,
                        SocketFlags.None,
                        ref state._remoteEndPoint,
                        new AsyncCallback(AsyncReceive),
                        state);

                    Thread.Sleep(100);

                    state._receiveDone.WaitOne();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }

        /// <summary>
        /// ysl 异步接收
        /// </summary>
        /// <param name="ar"></param>
        private void AsyncReceive(IAsyncResult ar)
        {
            if (ar.IsCompleted)
            {
                try
                {
                    Console.WriteLine(1 + "line");
                    UdpState state = (UdpState)ar.AsyncState;
                    //远程发送过来的数据
                    state._dataLength = _udpSocket.EndReceiveFrom(ar, ref state._remoteEndPoint);
                    Console.WriteLine(2 + "line");
                    //完成接收
                    _udpSocket.BeginReceiveFrom(
                        state._data,
                        0,
                        UdpState._bufferSize,
                        SocketFlags.None,
                        ref state._remoteEndPoint,
                        new AsyncCallback(AsyncReceive),
                        state);
                    Console.WriteLine(3 + "line");
                    //获取到的报文
                    string receiveString = Encoding.ASCII.GetString(state._data, 0, state._dataLength);
                    //当前处理完毕
                    Console.WriteLine(4 + "line");
                    Console.WriteLine(receiveString);
                    string str = "OK";
                    byte[] bytes = Encoding.ASCII.GetBytes(str.ToCharArray());
                    _udpSocket.SendTo(bytes, state._remoteEndPoint);

                    state._receiveDone.Set();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
    }
}

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace AsyncUdpSever
{
    public class UdpState
{
    public const int _bufferSize = 4096;

    public byte[] _data;

    public int _dataLength;

    public EndPoint _remoteEndPoint;

    public UdpState()
    {
        this._data = new byte[_bufferSize];

        _remoteEndPoint = (EndPoint)new IPEndPoint(IPAddress.Any, 0);
    }

    public UdpState(byte[] data, EndPoint remoteEndPoint)
    {
        this._data = data;
        this._dataLength = data.Length;
        this._remoteEndPoint = remoteEndPoint;
    }

    public ManualResetEvent _receiveDone = new ManualResetEvent(false);

}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值