天宇

学习日志

导航

C# udp 通信 例子

    大家好,这是我最近写了一个Udp通信的小程序,发表出来和大家共同学习,我希望和大家共同进步。

    upd通信接受端:

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

namespace Zhty.Socket.UDPSocket
{
   public  class UDP_Client
    {
        #region 属性
        private IPAddress _ClientAddress = IPAddress.Any;
        private int _ClientPort = 0;
        private byte[] _data = new byte[] { };
        public IPEndPoint Client
        {

            get { return new IPEndPoint(_ClientAddress, _ClientPort); }
            set
            {
                _ClientAddress = value.Address;
                _ClientPort = value.Port;
            }

        }

        public IPAddress ClientAddress
        {

            get
            {
                return _ClientAddress;

            }
            set
            {
                _ClientAddress = value;

            }

        }


        public int ClientPort
        {

            get { return _ClientPort; }
            set { _ClientPort = value; }

        }

        #endregion

        #region 方法
        public void SendMessage(byte[] message)
        {
            //' Encode message per settings

            // ' Send the message
            _data = message;
            try
            {
                SendUDPMessage(_data);
            }
            catch (Exception ex)
            { throw ex; }


        }

        private int SendUDPMessage(Byte[] _data)
        {
            //' Create a UDP Server and send the message, then clean up
            UdpClient _UDPServer = null;
            int ReturnCode;
            try
            {
                _UDPServer = new UdpClient();
                ReturnCode = 0;
                _UDPServer.Connect(Client);
                ReturnCode = _UDPServer.Send(_data, _data.Length);
            }
            catch (Exception ex)
            { throw ex; }
            finally
            {
                if (_UDPServer != null)
                {
                    _UDPServer.Close();
                }
            }
            return ReturnCode;
        }

 

        #endregion

    }
}

udp通信的发送端:
 
  using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;

namespace Zhty.Socket.UDPSocket
{
    public class UDP_Server
    {
       
        private Thread _ThreadReceive;
        private int _ClientPort = 0;
        private string _Message = null;
        
        private UdpClient _UDPClient;
        private IPEndPoint _Server = new IPEndPoint(IPAddress.Any, 0);
        private int _BytesReceived = 0;

        #region 事件定义
        public delegate void OnReceivedDataHandler(object sender, DataReceivedEventArgs e);
        public event OnReceivedDataHandler OnRecivedData;

        public delegate void OnStateChangedHandler(object sender, ServerStateChangeEventArgs e);
        public event OnStateChangedHandler OnStateChanged;

        

        #endregion
        #region 属性

         int _bufferSize = 1024;
        public  int BufferSize
        {
            get { return _bufferSize; }
            set { _bufferSize = value; }
        }
        public int BytesReceived
        {
            get { return _BytesReceived; }

        }
        public string Message
        {
            get { return _Message; }
        }

        public int ClientPort
        {
            get { return _ClientPort; }
            set { _ClientPort = value; }
        }
        
        #endregion
        #region 方法
        void DataReceiveProc()
        {
            //BeforeReceive(this,new EventArgs());
            _Message = "";
            byte[] data = new byte[BufferSize];
            try
            {
               
              
                data = _UDPClient.Receive(ref _Server);
                
                 if (OnRecivedData != null)
                    OnRecivedData(this, new DataReceivedEventArgs(data));
                 System.Threading.Thread.Sleep(100);
            }
            catch (Exception ex)
            {
               
                 if (OnStateChanged != null)
                    OnStateChanged(this, new ServerStateChangeEventArgs(false));
                throw ex;
            }
            finally {
           
            InitializeThread();
           
           
            }
          
            
        }
        private void InitializeClient()
        {
            if (_UDPClient == null)
            {
                this._UDPClient = new UdpClient(ClientPort);
            }
            
       
        }
        private void InitializeThread()
        {
            try
            {
                _ThreadReceive = new Thread(new ThreadStart(DataReceiveProc));
                _ThreadReceive.Start();
            }
            catch(Exception ex) {

                throw ex;
            }
        }
        public void Start()
        {
            InitializeClient();
            InitializeThread();
        }
        #endregion
        public void Stop()
        {

            try
            {

                
                _ThreadReceive.Abort();
                if (_UDPClient != null)
                {
                    // ' Close the UDPClient and then force it to Nothing
                   
                    _UDPClient.Close();
                    _UDPClient = null;
                }
            }
            catch (Exception ex)
            {
                throw ex;

            }
       
        }
        #region 析构方法
        ~UDP_Server()
        {
            Stop();
        }
        #endregion

    }
}


辅助类:


using System;
using System.Collections.Generic;
using System.Text;

namespace Zhty.Socket.UDPSocket
{
    public class DataReceivedEventArgs : EventArgs
    {
        public DataReceivedEventArgs(byte[] data)
        {
            Data = data;
        }

        byte[] m_Data;
        public byte[] Data
        {
            get { return m_Data; }
            set { m_Data = value; }
        }
    }


    public class ServerStateChangeEventArgs : EventArgs
    {
        public ServerStateChangeEventArgs(bool state)
        {
            Running = state;
        }

        bool m_Running;
        public bool Running
        {
            get { return m_Running; }
            set { m_Running = value; }
        }
    }
}

posted on 2006-11-03 16:46  绿洲  阅读(10772)  评论(1编辑  收藏  举报