UDP接收实例

来源:互联网 发布:淘宝店怎么提升销量 编辑:程序博客网 时间:2024/05/01 07:05
1.通讯类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace UDPDataPack
{
   public class UDPCommunication
    {
        public UDPCommunication(int port,int timeOut)
        {
            this.LocalReceivePort = port;
            udpClient = new UdpClient(port);
            udpClient.Client.ReceiveTimeout = timeOut;
            receiveTimeOut = timeOut;
        }
     public UdpClient udpClient=null;
     public string LocalIP = null;
     public int LocalReceivePort;
     public int receiveTimeOut;
     public byte[] DataByte;
      public bool Flag=false;

     public byte[] receive()//接收
     {
         if (udpClient.Client == null)
         {
             udpClient = new UdpClient(LocalReceivePort);
             udpClient.Client.ReceiveTimeout = receiveTimeOut;
         }
             UdpClient udpClientTemp = udpClient;
           
             IPEndPoint ipeEndPoint = null;
             try
             {
                
                 byte[] bytes = udpClientTemp.Receive(ref ipeEndPoint);
                 DataByte = bytes;
                 udpClientTemp.Close();
                 //if (!Analyse.DecideCompletePack(bytes))
                 //{
                 //return DataByte=new byte[0];
                 //}
                 return DataByte;
             }
             catch
             {
                 return new byte[0];
             }      
        
       
     }
     public  void start()
     {
       
        receive();
      
    
     }
       public void stop()
       {
           Flag = true;
         
       }
    }
  
}


2.调用



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Net;
using System.Threading;
namespace UDPDataPack
{
    public partial class UDPTestForm : Form
    {
        public UDPTestForm()
        {
            InitializeComponent();
            string vertionStr = ConfigurationManager.AppSettings["ID"] + "      " + ConfigurationManager.AppSettings["Description"];
            this.Text = vertionStr;
            this.LocalIPAdress.Text = GetIP();
           textBoxPlayEvent = textBoxWrite;
           //textBoxPlayEvent2 = textBoxWrite2;
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        public Analyse analyse = new Analyse(DataMemoryModel.LittleEndian);
       public event textBoxCallBack textBoxPlayEvent;
       //public event textBoxCallBack2 textBoxPlayEvent2;
        public Thread th;
        public bool stopFlag=false;
        UDPCommunication udpCommnication = null;


        public static string GetIP()//获取主机IP
        {
            string strAddr = "";
            try
            {
                string strHostName = System.Net.Dns.GetHostName();
                System.Net.IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
                foreach (IPAddress _ipaddress in ipEntry.AddressList)
                {
                    if (_ipaddress.AddressFamily.ToString().ToLower() == "internetwork")
                    {
                        strAddr = _ipaddress.ToString();
                        break;
                    }
                }
           
            }
            catch (System.Exception e)
            {
              throw e;
            }
            return strAddr;
        }
        private void buttonSingleReceive_Click(object sender, EventArgs e)//单次接收
        {
           

        }
        private void buttonStart_Click(object sender, EventArgs e)//循环接收
        {
            stopFlag = false;
            int receivePort = Convert.ToInt32(this.LocaclReceivePort.Text);
            int receiveTimeOut = Convert.ToInt32(this.textBoxReceiveTimeOut.Text);
            if(udpCommnication==null)
            {
            udpCommnication =new UDPCommunication(receivePort, receiveTimeOut);
            }
            this.th = new Thread(threadFuction);
              th.Start();
              //udpCommnication.udpClient.Close();
        }
        //public void threadRun()
        //{
        //    MethodInvoker In = new MethodInvoker(threadFuction);
        //   this.BeginInvoke(In);
       
        //}

        public void threadFuction()
        {
            while (!stopFlag)
            {             
                if (udpCommnication == null)
                {
                    int receivePort = Convert.ToInt32(this.LocaclReceivePort.Text);
                    int receiveTimeOut = Convert.ToInt32(this.textBoxReceiveTimeOut.Text);
                    udpCommnication = new UDPCommunication(receivePort, receiveTimeOut);
                }

                try
                {
                    byte[] receiv = udpCommnication.receive();
                    //string content = Encoding.Default.GetString(receiv);
                    //this.textBoxPlayEvent(receiv);
                    textBoxWrite(receiv);
                    //this.textBoxPlayEvent2(content );
                }
                catch
                {

                }
            }
        }
        public delegate void textBoxCallBack(byte[] content);
        public delegate void textBoxCallBack2(string content);
        public void textBoxWrite2(string content)
        {
            this.textBoxContent.AppendText(content  + Environment.NewLine);
        }

0 0