• C# UDP 连接通信 简单示例


    Udp.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    using System.Net.Sockets;
    
    namespace udp
    {
        public delegate void UdpEventHandler(object sender, UdpEventArgs e);
    
        public abstract class Udp : IUdp
        {
            public event UdpEventHandler Received;
    
            private int _port;
            private string _ip;
            public bool IsListening { get; private set; }
            private Socket _sck;
    
            public Socket UdpSocket
            {
                get { return _sck; }
            }
            public string Ip
            {
                get { return _ip; }
                set { _ip = value; }
            }
            public int Port
            {
                get { return _port; }
                set
                {
                    if (value < 0)
                        value = 0;
                    if (value > 65536)
                        value = 65536;
                    _port = value;
                }
            }
    
            public Udp()
            {
                _sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                _sck.ReceiveBufferSize = UInt16.MaxValue * 8;
                //log
                System.Diagnostics.Trace.Listeners.Clear();
                System.Diagnostics.Trace.AutoFlush = true;
                System.Diagnostics.Trace.Listeners.Add(new System.Diagnostics.TextWriterTraceListener("log.txt"));
            }
    
    
            public void Listening()
            {
                IPAddress ip = IPAddress.Any;
                try
                {
                    if (this._ip != null)
                        if (!IPAddress.TryParse(this._ip, out ip))
                            throw new ArgumentException("IP地址错误", "Ip");
                    _sck.Bind(new IPEndPoint(ip, this._port));
    
                    UdpState state = new UdpState();
                    state.Socket = _sck;
                    state.Remote = new IPEndPoint(IPAddress.Any, 0);
                    _sck.BeginReceiveFrom(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, ref state.Remote, new AsyncCallback(EndReceiveFrom), state);
                    IsListening = true;
                }
                catch (ArgumentException ex)
                {
                    IsListening = false;
                    System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString() + "	" + ex.Message);
                    throw ex;
                }
                catch (Exception ex)
                {
                    IsListening = false;
                    System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString() + "	" + ex.Message);
                    throw ex;
                }
            }
            private void EndReceiveFrom(IAsyncResult ir)
            {
                if (IsListening)
                {
                    UdpState state = ir.AsyncState as UdpState;
                    try
                    {
                        if (ir.IsCompleted)
                        {
                            int length = state.Socket.EndReceiveFrom(ir, ref state.Remote);
                            byte[] btReceived = new byte[length];
                            Buffer.BlockCopy(state.Buffer, 0, btReceived, 0, length);
                            OnReceived(new UdpEventArgs(btReceived, state.Remote));
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString() + "	" + ex.Message+ex.Source);
                    }
                    finally
                    {
                        state.Socket.BeginReceiveFrom(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, ref state.Remote, new AsyncCallback(EndReceiveFrom), state);
                    }
                }
            }
    
            private void OnReceived(UdpEventArgs e)
            {
                if (this.Received != null)
                {
                    Received(this, e);
                }
            }
    
            public void Send(byte[] bt, EndPoint ep)
            {
                if (_sck == null) return;
                try
                {
                    this._sck.SendTo(bt, ep);
                }
                catch (SocketException ex)
                {
                    System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString() + "	" + ex.Message);
                    throw ex;
                }
            }
    
            public void Dispose()
            {
                if (_sck == null) return;
    
                  using (_sck) ;
                //this.IsListening = false;
                //this._sck.Blocking = false;
                //this._sck.Shutdown(SocketShutdown.Both);
                //this._sck.Close();
                //this._sck = null;
            }
    
        }
    }
    View Code

    IUdp.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net.Sockets;
    using System.Net;
    
    namespace udp
    {
        public interface IUdp : IDisposable
        {
            event UdpEventHandler Received;
    
            void Send(byte[] bt, EndPoint ep);
    
            Socket UdpSocket { get; }
        }
    }
    View Code

    UdpEventArgs.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    
    namespace udp
    {
        public class UdpEventArgs : EventArgs
        {
            private EndPoint _remote;
    
            private byte[] _rec;
    
            public byte[] Received
            {
                get { return _rec; }
            }
            public EndPoint Remote
            {
                get { return _remote; }
            }
    
            public UdpEventArgs(byte[] data, EndPoint remote)
            {
                this._remote = remote;
                this._rec = data;
            }
        }
    }
    View Code

    UdpState.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    using System.Net.Sockets;
    
    namespace udp
    {
        internal class UdpState
        {
            public byte[] Buffer;
            public EndPoint Remote;
            public Socket Socket;
    
            public UdpState()
            {
                Buffer = new byte[65536];
            }
        }
    }
    View Code

    Client

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net.Sockets;
    using System.Net;
    using udp;
    namespace client
    {
        class Program
        { 
            private const string _serverIp = "127.0.0.1";
            private const int _serverPort = 8000;
    
            static void Main(string[] args)
            {
                Client client = new Client();
                client.ep = new IPEndPoint(IPAddress.Parse(_serverIp), _serverPort);
                client.Listening();
                client.Received += new UdpEventHandler(client_Received);
                while (true)
                {
                    string tmp = Console.ReadLine();
                    for (int i = 0; i < 10; i++)
                    {
                        byte[] bt = Encoding.Default.GetBytes(tmp + i);
                        System.Threading.Thread t = new System.Threading.Thread(() =>
                        {
                            client.Send(bt, client.ep);
                        });
                        t.Start();
                    }
                    client.Dispose();
                }
            }
    
            static void client_Received(object sender, UdpEventArgs e)
            {
                IPEndPoint ep = e.Remote as IPEndPoint;
                string tmpReceived = Encoding.Default.GetString(e.Received);
                Console.WriteLine(ep.Address.ToString() + ":" + ep.Port + "--> " + tmpReceived);
            }
        }
    
        public class Client : Udp
        {
            public EndPoint ep;
            public Client()
            {
    
            }
        }
    }
    View Code

    Server

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using System.Net.Sockets;
    using System.Net;
    using udp;
    
    namespace server
    {
        class Program
        { 
            static Server server = new Server();
            static void Main(string[] args)
            {
                server.Port = 8000;
                server.Listening();
                if (server.IsListening)
                {
                    server.Received += new UdpEventHandler(server_Received);
                }
                Console.ReadKey();
            }
    
            static void server_Received(object sender, UdpEventArgs e)
            {
                IPEndPoint ep = e.Remote as IPEndPoint;
                string tmpReceived = Encoding.Default.GetString(e.Received);
                Console.WriteLine(ep.Address.ToString() + ":" + ep.Port + "--> " + tmpReceived);
                ///自动回复
                server.Send(Encoding.Default.GetBytes("服务器已收到数据:'" + tmpReceived + "',来自:‘" + ep.Address.ToString() + ":" + ep.Port + ""), ep);
            }
    
        }
        public class Server : Udp
        {
            private EndPoint ep;
            public Server()
            {
            }
        }
    }
    View Code

    源码文件

  • 相关阅读:
    .NET中TreeView控件从数据库获取数据源
    .NET中GridView控件的全选删除
    TreeView无限极分类绑定(从数据库读取数据源)
    .NET中GridView代码更改列名
    .NET读写cookie方法
    .NET中GridView控件的高亮显示和删除前弹框提示
    Repeater控件的多层嵌套,DataList控件的多层嵌套
    .NET一些常用的语句集合(不断更新中)
    解决IE5、IE6、IE7与W3C标准的冲突,使用(IE7.js IE8.js)兼容
    kindeditor富文本编辑器ASP.NET源码下载
  • 原文地址:https://www.cnblogs.com/wjshan0808/p/4718737.html
Copyright © 2020-2023  润新知