SocketStream.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.IO;
  3. using System.Net.Sockets;
  4. namespace SocketHttpListener
  5. {
  6. public class SocketStream : Stream
  7. {
  8. private readonly Socket _socket;
  9. public SocketStream(Socket socket, bool ownsSocket)
  10. {
  11. _socket = socket;
  12. }
  13. public override void Flush()
  14. {
  15. }
  16. public override bool CanRead => true;
  17. public override bool CanSeek => false;
  18. public override bool CanWrite => true;
  19. public override long Length => throw new NotImplementedException();
  20. public override long Position
  21. {
  22. get => throw new NotImplementedException();
  23. set => throw new NotImplementedException();
  24. }
  25. public override void Write(byte[] buffer, int offset, int count)
  26. {
  27. _socket.Send(buffer, offset, count, SocketFlags.None);
  28. }
  29. public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  30. {
  31. return _socket.BeginSend(buffer, offset, count, SocketFlags.None, callback, state);
  32. }
  33. public override void EndWrite(IAsyncResult asyncResult)
  34. {
  35. _socket.EndSend(asyncResult);
  36. }
  37. public override void SetLength(long value)
  38. {
  39. throw new NotImplementedException();
  40. }
  41. public override long Seek(long offset, SeekOrigin origin)
  42. {
  43. throw new NotImplementedException();
  44. }
  45. public override int Read(byte[] buffer, int offset, int count)
  46. {
  47. return _socket.Receive(buffer, offset, count, SocketFlags.None);
  48. }
  49. public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  50. {
  51. return _socket.BeginReceive(buffer, offset, count, SocketFlags.None, callback, state);
  52. }
  53. public override int EndRead(IAsyncResult asyncResult)
  54. {
  55. return _socket.EndReceive(asyncResult);
  56. }
  57. }
  58. }