private void ListenForClients() { while (!shouldStop) { try { byte[] buffer = new byte[Constants.DATAGRAM_DATA_SIZE]; EndPoint remoteEndPoint = (EndPoint) new IPEndPoint(IPAddress.Any, 0); int bytesRead = socket.ReceiveFrom(buffer, ref remoteEndPoint); byte[] data = new byte[bytesRead]; Array.Copy(sourceArray: buffer, destinationArray: data, length: bytesRead); //we have the message and the address of the remote endpoint so pass it to anyone interested UdpDataReceiveEventArgs args = new UdpDataReceiveEventArgs(data, (IPEndPoint)remoteEndPoint); OnDataReceive(args); } catch (SocketException ex) { if (ex.SocketErrorCode != SocketError.TimedOut) { //if a socket error other than timeout occurs, pass the error to anyone interested - do not break the server loop! UdpDataReceiveErrorEventArgs args = new UdpDataReceiveErrorEventArgs(ex); OnDataReceiveError(args); } } catch (Exception) { //close socket if (socket != null) { socket.Close(); socket = null; } //and rethrow throw; } Thread.Sleep(1); }//while (!shouldStop) if (socket != null) { socket.Close(); socket = null; } }
protected virtual void OnDataReceiveError(UdpDataReceiveErrorEventArgs e) { DataReceiveError?.Invoke(this, e); }