|
1 |
| -require_relative '../lib/iou' |
| 1 | +require_relative '../lib/uringmachine' |
2 | 2 | require 'socket'
|
3 | 3 |
|
4 | 4 | socket = TCPServer.open('127.0.0.1', 1234)
|
5 | 5 | puts 'Listening on port 1234...'
|
6 | 6 |
|
7 |
| -@ring = IOU::Ring.new |
| 7 | +$machine = UringMachine.new |
| 8 | +$bgid = $machine.setup_buffer_ring(4096, 1024) |
8 | 9 |
|
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) |
33 | 13 | 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 |
34 | 18 | end
|
35 | 19 |
|
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}" |
48 | 24 | end
|
49 | 25 | end
|
50 | 26 |
|
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