zoukankan      html  css  js  c++  java
  • 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

    源码文件

  • 相关阅读:
    Springboot | 私人订制你的banner
    模块化系列教程 | 深入源码分析阿里JarsLink1.0模块化框架
    Nutz | Nutz项目整合Spring实战
    Shrio | java.io.IOException: Resource [classpath:shiro.ini] could not be found
    手把手写框架入门(一) | 核心拦截器DispatchFilter实现
    Rabbitmq | ConnectionException:Connection refused: connect
    Spring Cloud学习总结(非原创)
    Spring Cloud Stream介绍-Spring Cloud学习第八天(非原创)
    Spring Cloud Bus介绍--Spring Cloud学习第七天(非原创)
    分布式配置中心介绍--Spring Cloud学习第六天(非原创)
  • 原文地址:https://www.cnblogs.com/wjshan0808/p/4718737.html
Copyright © 2011-2022 走看看