socketstream.monkey2 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. Namespace std.socket
  2. Class SocketStream Extends std.stream.Stream
  3. #rem monkeydoc Creates a new socketsteam from an existing socket.
  4. Note: Closing the stream will also close the socket.
  5. #end
  6. Method New( socket:Socket )
  7. _socket=socket
  8. End
  9. #rem monkeydoc The underlying socket.
  10. #end
  11. Property Socket:Socket()
  12. Return _socket
  13. End
  14. #rem monkeydoc True if socket has been closed.
  15. #end
  16. Property Eof:Bool() Override
  17. Return _socket.Closed
  18. End
  19. #rem monkeydoc Always 0.
  20. #end
  21. Property Position:Int() Override
  22. Return 0
  23. End
  24. #rem monkeydoc Always -1.
  25. #end
  26. Property Length:Int() Override
  27. Return -1
  28. End
  29. #rem monkeydoc Closes the socket.
  30. #end
  31. Method OnClose() Override
  32. _socket.Close()
  33. End
  34. #rem monkeydoc No operation.
  35. #end
  36. Method Seek( position:Int ) Override
  37. End
  38. #rem monkeydoc Reads data from the socket stream.
  39. Reads at most `count` bytes from the socket.
  40. Returns 0 if the socket has been closed by the peer.
  41. Can return less than `count`, in which case you may have to read again if you know there's more data coming.
  42. @param buf The memory buffer to read data into.
  43. @param count The number of bytes to read from the socket stream.
  44. @return The number of bytes actually read.
  45. #end
  46. Method Read:Int( buf:Void Ptr,count:Int ) Override
  47. Return _socket.Receive( buf,count )
  48. End
  49. #rem monkeydoc Writes data to the socket stream.
  50. Writes `count` bytes to the socket.
  51. Returns the number of bytes actually written.
  52. Can return less than `count` if the socket has been closed by the peer or if an error occured.
  53. @param buf The memory buffer to write data from.
  54. @param count The number of bytes to write to the socket stream.
  55. @return The number of bytes actually written.
  56. #end
  57. Method Write:Int( buf:Void Ptr,count:Int ) Override
  58. Local sent:=0
  59. While count>0
  60. Local n:=_socket.Send( buf,count )
  61. If n<0 Exit
  62. buf=Cast<Byte Ptr>( buf )+n
  63. count-=n
  64. sent+=n
  65. Wend
  66. Return sent
  67. End
  68. Private
  69. Field _socket:Socket
  70. End