You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

37 lines
1.1 KiB

  1. using System;
  2. using System.IO.Pipelines;
  3. using System.Net.Sockets;
  4. namespace MQTTnet.AspNetCore.Client.Tcp
  5. {
  6. public class SocketReceiver
  7. {
  8. private readonly Socket _socket;
  9. private readonly SocketAsyncEventArgs _eventArgs = new SocketAsyncEventArgs();
  10. private readonly SocketAwaitable _awaitable;
  11. public SocketReceiver(Socket socket, PipeScheduler scheduler)
  12. {
  13. _socket = socket;
  14. _awaitable = new SocketAwaitable(scheduler);
  15. _eventArgs.UserToken = _awaitable;
  16. _eventArgs.Completed += (_, e) => ((SocketAwaitable)e.UserToken).Complete(e.BytesTransferred, e.SocketError);
  17. }
  18. public SocketAwaitable ReceiveAsync(Memory<byte> buffer)
  19. {
  20. #if NETCOREAPP2_1
  21. _eventArgs.SetBuffer(buffer);
  22. #else
  23. var segment = buffer.GetArray();
  24. _eventArgs.SetBuffer(segment.Array, segment.Offset, segment.Count);
  25. #endif
  26. if (!_socket.ReceiveAsync(_eventArgs))
  27. {
  28. _awaitable.Complete(_eventArgs.BytesTransferred, _eventArgs.SocketError);
  29. }
  30. return _awaitable;
  31. }
  32. }
  33. }