【发布时间】:2011-05-06 07:35:25
【问题描述】:
我想这样做
for (int i = 0; i < 100; i++ )
{
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
}
但我必须使用UdpClient.BeginReceive,而不是使用UdpClient.Receive。问题是,我该怎么做?使用BeginReceive 的示例并不多,MSDN 示例根本没有帮助。我应该使用BeginReceive,还是在单独的线程下创建它?
我一直得到ObjectDisposedException 异常。我只收到发送的第一个数据。下一个数据会抛出异常。
public class UdpReceiver
{
private UdpClient _client;
public System.Net.Sockets.UdpClient Client
{
get { return _client; }
set { _client = value; }
}
private IPEndPoint _endPoint;
public System.Net.IPEndPoint EndPoint
{
get { return _endPoint; }
set { _endPoint = value; }
}
private int _packetCount;
public int PacketCount
{
get { return _packetCount; }
set { _packetCount = value; }
}
private string _buffers;
public string Buffers
{
get { return _buffers; }
set { _buffers = value; }
}
private Int32 _counter;
public System.Int32 Counter
{
get { return _counter; }
set { _counter = value; }
}
private Int32 _maxTransmission;
public System.Int32 MaxTransmission
{
get { return _maxTransmission; }
set { _maxTransmission = value; }
}
public UdpReceiver(UdpClient udpClient, IPEndPoint ipEndPoint, string buffers, Int32 counter, Int32 maxTransmission)
{
_client = udpClient;
_endPoint = ipEndPoint;
_buffers = buffers;
_counter = counter;
_maxTransmission = maxTransmission;
}
public void StartReceive()
{
_packetCount = 0;
_client.BeginReceive(new AsyncCallback(Callback), null);
}
private void Callback(IAsyncResult result)
{
try
{
byte[] buffer = _client.EndReceive(result, ref _endPoint);
// Process buffer
MainWindow.Log(Encoding.ASCII.GetString(buffer));
_packetCount += 1;
if (_packetCount < _maxTransmission)
{
_client.BeginReceive(new AsyncCallback(Callback), null);
}
}
catch (ObjectDisposedException ex)
{
MainWindow.Log(ex.ToString());
}
catch (SocketException ex)
{
MainWindow.Log(ex.ToString());
}
catch (System.Exception ex)
{
MainWindow.Log(ex.ToString());
}
}
}
什么给了?
顺便说一下,大致思路是:
- 创建 tcpclient 管理器。
- 开始使用 udpclient 发送/接收数据。
- 当所有数据都发送完毕后,tcpclient 管理器将向接收方发出所有数据已发送的信号,并且应关闭 udpclient 连接。
【问题讨论】:
-
您当然知道 UDP 是一种可以丢失数据包的协议,并且不保证唯一性和顺序,因此尝试从特定端点接收 100 个数据包并不一定意味着您收到了相同的 100 个数据包按顺序发送的数据包?也许你应该使用 TCP?
-
我非常清楚这一点。这样做的原因是因为,我想分析两方之间的连接,即带宽估计。
-
socket beginreceive (async) in loop 很难实现,可以尝试使用 NetworkStream.DataAvailable 组合进行同步循环。提示:您可以将 BeginSend (async) 与相同的套接字一起使用。
标签: c# udpclient beginreceive