c#中UDP數據發送和接收

 

 

 

 /**********************
* 功能:UDP數據發送和接收
* 作者:雲濤
* 時間:20070820
* 地點:北京
*********************
*/



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

namespace IM.Controls
{

    
public class ClsUDPSrv
    
{

        
public ClsUDPSrv()
        
{
            IsDispose 
= false;
        }


        
public UdpClient UDP_Srv = new UdpClient();
        
public static int UDPServer_Port = 2007;
        privateint UDPClient_Port;
        
private Thread td_Udp;
        
private IPEndPoint IPEP_Srv = new IPEndPoint(IPAddress.Any, 0);
        
public delegate void DataControlEventHandler(byte[] Data, System.Net.IPAddress Ip, int Port);
        
public event DataControlEventHandler DataControl;
        
public delegate void Udp_ErrorEventHandler(string Error);
        
public event Udp_ErrorEventHandler Udp_Error;
        
public bool IsDispose = false;

        
public void Listen(int Port)
        
{
            
try
            
{
                IsDispose 
= false;
                UDPClient_Port 
= Port;
                UDP_Srv 
= new UdpClient(Port);
                td_Udp 
= new Thread(new ThreadStart(UDPDataControl));
                td_Udp.IsBackground 
= true;
                td_Udp.Start();
            }

            
catch (Exception ex)
            
{
                
if (Udp_Error != null)
                    Udp_Error(ex.ToString());
            }

        }


        
private void ReceiveDataControl()
        
{
            
while (!IsDispose)
            
{
                
try
                
{
                    
byte[] Data = UDP_Srv.Receive(ref IPEP_Srv);
                    
if (DataControl != null)
                        DataControl(Data, IPEP_Srv.Address, IPEP_Srv.Port);
                    Thread.Sleep(
0);
                }

                
catch (Exception ex)
                
{
                    
if (Udp_Error != null)
                        Udp_Error(ex.ToString());
                }

            }

        }


        
public void SendData(System.Net.IPAddress Host, int Port, byte[] Data)
        
{
            
try
            
{
                IPEndPoint server 
= new IPEndPoint(Host, Port);
                UDP_Srv.Send(Data, Data.Length, server);

            }

            
catch (Exception ex)
            
{
                
if (Udp_Error != null)
                    Udp_Error(ex.ToString());
            }

        }


 

        
public void Dispose()
        
{
            Thread.Sleep(
30);
            
try
            
{
                IsDispose 
= true;
                UDP_Srv.Close();
                td_Udp.Abort();
            }

            
catch (Exception ex)
            
{
                
if (Udp_Error != null)
                    Udp_Error(ex.ToString());
            }

        }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章