comparison net/http/server/stream.rb @ 0:1eef88068f9f tip

initial commit of maze game source
author ferencd
date Sun, 15 Sep 2019 11:46:47 +0200
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:1eef88068f9f
1 require 'net/protocol'
2
3 module Net
4 class HTTP < Protocol
5 module Server
6 #
7 # Handles reading and writing to raw HTTP streams.
8 #
9 # @since 0.2.0
10 #
11 class Stream
12
13 include Enumerable
14
15 # The raw socket of the stream.
16 attr_reader :socket
17
18 #
19 # Creates a new stream.
20 #
21 # @param [TCPSocket] socket
22 # The raw socket that will be read/write to.
23 #
24 # @since 0.2.0
25 #
26 def initialize(socket)
27 @socket = socket
28 end
29
30 #
31 # Reads data from the stream.
32 #
33 # @param [Integer] length
34 # The number of bytes to read.
35 #
36 # @param [#<<] buffer
37 # The optional buffer to append the data to.
38 #
39 # @return [String, nil]
40 # A chunk from the stream.
41 #
42 # @since 0.2.0
43 #
44 def read(length=4096,buffer='')
45 @socket.read(length,buffer)
46 end
47
48 #
49 # Reads each chunk from the stream.
50 #
51 # @yield [chunk]
52 # The given block will be passed each chunk.
53 #
54 # @yieldparam [String] chunk
55 # A chunk from the stream.
56 #
57 # @return [Enumerator]
58 # If no block is given, an Enumerator will be returned.
59 #
60 # @since 0.2.0
61 #
62 def each
63 return enum_for unless block_given?
64
65 while (chunk = read)
66 yield chunk
67 end
68 end
69
70 #
71 # Reads the entire body.
72 #
73 # @return [String]
74 # The complete body.
75 #
76 # @since 0.2.0
77 #
78 def body
79 buffer = ''
80
81 each { |chunk| buffer << chunk }
82 return buffer
83 end
84
85 #
86 # Writes data to the stream.
87 #
88 # @param [String] data
89 # The data to write to the stream.
90 #
91 # @return [Integer]
92 # The length of the data written.
93 #
94 # @since 0.2.0
95 #
96 def write(data)
97 result = @socket.write(data)
98
99 @socket.flush
100 return result
101 end
102
103 #
104 # @see #write
105 #
106 # @since 0.2.0
107 #
108 def <<(data)
109 write(data)
110 end
111
112 #
113 # Closes the stream.
114 #
115 # @since 0.2.0
116 #
117 def close
118 end
119
120 end
121 end
122 end
123 end