日期:2014-05-17 浏览次数:20903 次
UdpClient sender = new UdpClient();
--sender.Client.ReceiveTimeout = 0;
--sender.Client.ReceiveTimeout = -1;
--sender.Client.ReceiveTimeout = 1;
sender.Receive(ref remoteEP);
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
namespace GDPreAlarm
{
/// <summary>
/// clsUdp 的摘要说明。
/// </summary>
public class clsUdpSetParam
{
private Socket m_udp = null;
private AsyncCallback receiveCallback = null;
private EndPoint remoteEP = null;
private byte []buff=null;
public delegate void RecievedDataHandler(EndPoint ep,string strMessage);
public event RecievedDataHandler RecievedData;
internal clsUdpSetParam()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 接收线程
/// </summary>
/// <param name="ar"></param>
internal void OnDataReceived(IAsyncResult ar)
{
if(m_udp==null)
return;
try
{
Socket udpSocket = ar.AsyncState as Socket;
if(m_udp==null)
return;
int bytesRecved = udpSocket.EndReceiveFrom(ar, ref remoteEP);
lock(this)
{
string strData=System.Text.Encoding.Default.GetString(buff);
strData=strData.TrimEnd('\0');
if(RecievedData!=null)
{
RecievedData(remoteEP,strData);
}
for(int i=0;i<buff.Length;i++)
{
buff[i]=(byte)'\0';
}
}
}
catch(Exception ex)
{
}
finally
{
if(m_udp!=null)
{
try
{
m_udp.BeginReceiveFrom(buff, 0, buff.Length, SocketFlags.None,
ref remoteEP, receiveCallback, m_udp);
}
catch
{
}
}
}
}
public void Init()
{
buff=new byte[512];
IPEndPoint localIpEndPoint = new IPEndPoint(IPAddress.Parse(global.g_ServerToUpload.IP),global.g_ServerToUpload.Port);
remoteEP = new IPEndPoint(IPAddress.Any, 0);
if(m_udp!=null)
{
m_udp.Close();
m_udp=null;
}
m_udp = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
receiveCallback = new AsyncCallback(OnDataReceived);
m_udp.Bind(localIpEndPoint);
}
public void UnInit()
{
if(m_udp!=null)
{
m_udp.Close();
m_udp=null;
}
}
public bool SetParam(string strParam,EndPoint epClient)
{
if(m_udp==nu