UDP怎样检测回应是否TIMEOUT?

core0 2008-08-19 11:54:14
//发送部分
public void Send(String sMsg)
{
this.receive_ip();
System.Net.IPEndPoint iep = new System.Net.IPEndPoint(IPAddress.Parse(s_address), i_port);
th = new Thread(new ThreadStart(receive_ip));
th.IsBackground = true;
th.Start();
th.join(2500);
byte[] a = Encoding.UTF8.GetBytes(sMsg);
uc.Send(a, a.Length, iep);
}
//接收部分
public string Receive()
{
while (true)
{
Data = null;
if (th.IsAlive)
{
uc.Close();
uc = new System.Net.Sockets.UdpClient();
Data = "timeout";
}
else
{
Data = Encoding.UTF8.GetString(uc.Receive(ref iep));
}
return Data;
}
}
我这个方法检测不到TIMEOUT,各位还有什么其他方法吗?
...全文
554 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
core0 2008-08-20
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 wdgphc 的回复:]
Lz说的超时是Server的包超时clientm没有收到还是 Client的回复包超时Server没有收到
[/Quote]

是设备收到我信息然后它回应的超时
core0 2008-08-19
  • 打赏
  • 举报
回复
我的代码是发到一个无线设备上,然后这个设备就返回一个代码,假如我SEND到设备上,但超时也拿不到回应怎么办?
lextm 2008-08-19
  • 打赏
  • 举报
回复
异步的还需要检测超时?

下面的代码是同步的,摘自#SNMP

/// <summary>
/// Sends this <see cref="GetRequestMessage"/> and handles the response from agent.
/// </summary>
/// <param name="timeout">Timeout.</param>
/// <param name="port">Port number.</param>
/// <returns></returns>
public IList<Variable> Send(int timeout, int port)
{
byte[] bytes = _bytes;
IPEndPoint agent = new IPEndPoint(_agent, port);
using (UdpClient udp = new UdpClient())
{
udp.Send(bytes, bytes.Length, agent);
IPEndPoint from = new IPEndPoint(IPAddress.Any, 0);
IAsyncResult result = udp.BeginReceive(null, this);
result.AsyncWaitHandle.WaitOne(timeout, false);
if (!result.IsCompleted)
{
throw SharpTimeoutException.Create(_agent, timeout);
}

bytes = udp.EndReceive(result, ref from);
udp.Close();
}

MemoryStream m = new MemoryStream(bytes, false);
ISnmpMessage message = MessageFactory.ParseMessages(m)[0];
if (message.TypeCode != SnmpType.GetResponsePdu)
{
throw SharpOperationException.Create("wrong response type", _agent);
}

GetResponseMessage response = (GetResponseMessage)message;
if (response.SequenceNumber != SequenceNumber)
{
throw SharpOperationException.Create("wrong response sequence", _agent);
}

if (response.ErrorStatus != ErrorCode.NoError)
{
throw SharpErrorException.Create(
"error in response",
_agent,
response.ErrorStatus,
response.ErrorIndex,
response.Variables[response.ErrorIndex - 1].Id);
}

return response.Variables;
}


仅作参考。
wdgphc 2008-08-19
  • 打赏
  • 举报
回复
Lz说的超时是Server的包超时clientm没有收到还是 Client的回复包超时Server没有收到
lextm 2008-08-19
  • 打赏
  • 举报
回复
                if (!result.IsCompleted)
{
throw SharpTimeoutException.Create(_agent, timeout);
}


发送的函数会抛出超时异常。上面的代码只要正确处理这个异常就好了。收到回复,一切正常,没收到的话,在catch里面处理异常好了。
core0 2008-08-19
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 LQknife 的回复:]
自己设置个时间超时了显示错误信息呗 :-)
[/Quote]

知道怎样设置就不用发贴问了
LQknife 2008-08-19
  • 打赏
  • 举报
回复
自己设置个时间超时了显示错误信息呗 :-)

110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧