1

Why UDPClient.client.Availabe == 0 while the Wireshark can catch the UDP package ? I used the UDPClient to receive UDP package from other endpoint like below:

socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
socket.Bind(new IPEndPoint(IPAddress.Any, 1020));
socket.ReceiveTimeout = 100;
_udpReceiver = new UdpClient
{
    Client = socket
};

while (!_stopReceiveEvent.WaitOne(1))
{`your text`
    if (_udpReceiver.Available <= 0)
    {
        continue;
    }

    byte[] rawBytes = _udpReceiver.Receive(ref endPoint); 
    
    //handle the rawBytes
    //....
}

Most of time it worked normally, but occasionally the _udpReceiver.Avaiable equaled 0 while the Wireshark can catch the UDP package on 1020 port.

Any information? Thanks a lot in advance.

chaingun
  • 21
  • 2
  • 1
    in reality, `Socket.Available` (which is what this is exposing) is almost always the wrong thing to use *anyway*; maybe just... don't do that? just receive/receiveasync, and when the data arrives: it arrives. Re the `_stopReceiveEvent` - consider just disposing the socket in that scenario; that will interrupt any pending receive calls (I *suspect* that `Available` only makes sense for connection-based protocols, i.e. TCP, but even then: you should almost never use it for anything except choosing between a sync/async read) – Marc Gravell Jan 03 '23 at 13:23
  • Besides, I have closed all the firewalls. – chaingun Jan 03 '23 at 13:28
  • well, if you've blocked traffic at the firewall: don't expect to get any...? – Marc Gravell Jan 03 '23 at 13:30
  • (unrelated: but `UdpClient` is pretty pointless; you'd be better handling your own buffer, and just using `Socket` directly, tracking how much of the buffer was populated - rather than constantly allocating `byte[]` for right-sized buffers, which is what `UdpClient` is doing here) – Marc Gravell Jan 03 '23 at 13:32
  • I will remove "Socket.Available" and try the Socket.Receive() directly. – chaingun Jan 04 '23 at 08:26

0 Answers0