日期:2014-05-17  浏览次数:20903 次

c# udpclient 的recv时间问题
本帖最后由 assicen 于 2013-03-11 17:36:04 编辑

UdpClient sender = new UdpClient();
--sender.Client.ReceiveTimeout = 0;
--sender.Client.ReceiveTimeout = -1;
--sender.Client.ReceiveTimeout = 1;
sender.Receive(ref remoteEP);


ReceiveTimeout设置为0和-1 貌似会无限等待下去
即使设置为1 我在Receive前后输出时间 耗时也很长 (大概500ms)

有什么办法可以类似c++的recv异步 有没有数据都立即返回 不等待呢?

PS:类似BeginReceive的异步方法不太适合我的需求 就不要提了

------解决方案--------------------
直接用Socket多好啊,没这个问题
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