socketstream.monkey2 2.1 KB

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