/
server.cr
82 lines (78 loc) · 1.93 KB
/
server.cr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
class Socket
module Server
# Accepts an incoming connection and returns the client socket.
#
# ```
# require "socket"
#
# server = TCPServer.new(2202)
# while true
# socket = server.accept
# socket.puts Time.utc
# socket.close
# end
# ```
#
# If the server is closed after invoking this method, an `IO::Error` (closed stream) exception must be raised.
abstract def accept : IO
# Accepts an incoming connection and returns the client socket.
#
# Returns `nil` if the server is closed after invoking this method.
#
# ```
# require "socket"
#
# server = TCPServer.new(2202)
# while socket = server.accept?
# socket.puts Time.utc
# socket.close
# end
# ```
abstract def accept? : IO?
# Accepts an incoming connection and yields the client socket to the block.
# Eventually closes the connection when the block returns.
#
# Returns the value of the block. If the server is closed after invoking this
# method, an `IO::Error` (closed stream) exception will be raised.
#
# ```
# require "socket"
#
# server = TCPServer.new(2202)
# server.accept do |socket|
# socket.puts Time.utc
# end
# ```
def accept
sock = accept
begin
yield sock
ensure
sock.close
end
end
# Accepts an incoming connection and yields the client socket to the block.
# Eventually closes the connection when the block returns.
#
# Returns the value of the block or `nil` if the server is closed after
# invoking this method.
#
# ```
# require "socket"
#
# server = UNIXServer.new("/tmp/service.sock")
# server.accept? do |socket|
# socket.puts Time.utc
# end
# ```
def accept?
sock = accept?
return unless sock
begin
yield sock
ensure
sock.close
end
end
end
end