voglio fare questoCome utilizzare UdpClient.BeginReceive in un ciclo
for (int i = 0; i < 100; i++)
{
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
}
Ma invece di usare UdpClient.Receive
, devo usare UdpClient.BeginReceive
. Il problema è, come faccio? Non ci sono molti campioni che usano BeginReceive
e l'esempio MSDN non aiuta affatto. Dovrei usare BeginReceive
, o semplicemente crearlo in un thread separato?
ho sempre ottengo ObjectDisposedException
eccezione. Ricevo solo i primi dati inviati. I prossimi dati genereranno un'eccezione.
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());
}
}
}
Cosa dà?
Tra l'altro, l'idea generale è:
- Crea direttore TcpClient.
- Inizia l'invio/ricezione di dati tramite classe UdpClient.
- Quando tutti i dati è stato inviato, TcpClient gestore segnalerà ricevitore che tutti i dati sono stati inviati, e collegamento classe UdpClient dovrebbe essere chiusa.
Siete consapevoli, naturalmente, che UDP è un protocollo che può perdere i pacchetti e non garantisce l'unicità, né ordine, in modo da tentare di ricevere 100 pacchetti da uno specifico endpoint non necessariamente mezzi che hai ricevuto gli stessi 100 pacchetti, in ordine, che sono stati inviati? Forse dovresti usare il TCP? –
ne sono perfettamente consapevole. la ragione di questo è perché, voglio analizzare la connessione tra 2 parti, cioè la stima della larghezza di banda. –