Skip to content

Commit a8907c0

Browse files
committed
Rewrite echo server
1 parent 807debb commit a8907c0

File tree

1 file changed

+18
-40
lines changed

1 file changed

+18
-40
lines changed

examples/echo_server.rb

Lines changed: 18 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,30 @@
1-
require_relative '../lib/iou'
1+
require_relative '../lib/uringmachine'
22
require 'socket'
33

44
socket = TCPServer.open('127.0.0.1', 1234)
55
puts 'Listening on port 1234...'
66

7-
@ring = IOU::Ring.new
7+
$machine = UringMachine.new
8+
$bgid = $machine.setup_buffer_ring(4096, 1024)
89

9-
@ring.prep_accept(fd: socket.fileno, multishot: true) do |c|
10-
setup_connection(c[:result]) if c[:result] > 0
11-
end
12-
13-
def setup_connection(fd)
14-
puts "Connection accepted fd #{fd}"
15-
16-
buffer = +''
17-
echo_prep_read(fd, buffer)
18-
end
19-
20-
def echo_prep_read(fd, buffer)
21-
@ring.prep_read(fd: fd, buffer: buffer, len: 4096, buffer_offset: -1) do |c|
22-
if c[:result] > 0
23-
echo_lines(fd, buffer)
24-
echo_prep_read(fd, buffer)
25-
elsif c[:result] == 0
26-
puts "Connection closed by client on fd #{fd}"
27-
else
28-
puts "Got error #{c[:result]} on fd #{fd}, closing connection..."
29-
@ring.prep_close(fd: fd) do |c|
30-
puts "Connection closed on fd #{fd}, result #{c[:result]}"
31-
end
32-
end
10+
def handle_connection(fd)
11+
$machine.read_each(fd, $bgid) do |buf|
12+
$machine.write(fd, buf)
3313
end
14+
puts "Connection closed by client fd #{fd}"
15+
rescue Exception => e
16+
puts "Got error #{e.inspect}, closing connection"
17+
$machine.close(fd) rescue nil
3418
end
3519

36-
def echo_lines(fd, buffer)
37-
sep = $/
38-
sep_size = sep.bytesize
39-
40-
while true
41-
idx = buffer.index(sep)
42-
if idx
43-
line = buffer.slice!(0, idx + sep_size)
44-
@ring.prep_write(fd: fd, buffer: line)
45-
else
46-
break
47-
end
20+
$machine.spin do
21+
loop do
22+
$machine.sleep 5
23+
puts "pending: #{$machine.pending_count}"
4824
end
4925
end
5026

51-
trap('SIGINT') { exit! }
52-
@ring.process_completions_loop
27+
$machine.accept_each(socket.fileno) do |fd|
28+
puts "Connection accepted fd #{fd}"
29+
$machine.spin(fd) { handle_connection(_1) }
30+
end

0 commit comments

Comments
 (0)