| 1 | import os |
| 2 | import os.notify |
| 3 | import net |
| 4 | import time |
| 5 | |
| 6 | // This example demonstrates a single threaded TCP server using os.notify to be |
| 7 | // notified of events on file descriptors. You can connect to the server using |
| 8 | // netcat in separate shells, for example: `nc localhost 9001` |
| 9 | |
| 10 | fn main() { |
| 11 | $if !linux { |
| 12 | eprintln('This example only works on Linux') |
| 13 | exit(1) |
| 14 | } |
| 15 | |
| 16 | // create TCP listener |
| 17 | mut listener := net.listen_tcp(.ip, 'localhost:9001')! |
| 18 | defer { |
| 19 | listener.close() or {} |
| 20 | } |
| 21 | addr := listener.addr()! |
| 22 | eprintln('Listening on ${addr}') |
| 23 | eprintln('Type `stop` to stop the server') |
| 24 | |
| 25 | // create file descriptor notifier |
| 26 | mut notifier := notify.new()! |
| 27 | defer { |
| 28 | notifier.close() or {} |
| 29 | } |
| 30 | notifier.add(os.stdin().fd, .read)! |
| 31 | notifier.add(listener.sock.handle, .read)! |
| 32 | |
| 33 | for { |
| 34 | for event in notifier.wait(time.infinite) { |
| 35 | match event.fd { |
| 36 | listener.sock.handle { |
| 37 | // someone is trying to connect |
| 38 | eprint('trying to connect.. ') |
| 39 | if conn := listener.accept() { |
| 40 | notifier.add(conn.sock.handle, .read | .peer_hangup) or { |
| 41 | eprintln('error adding to notifier: ${err}') |
| 42 | return |
| 43 | } |
| 44 | eprintln('connected') |
| 45 | } else { |
| 46 | eprintln('unable to accept: ${err}') |
| 47 | } |
| 48 | } |
| 49 | 0 { |
| 50 | // stdin |
| 51 | s, _ := os.fd_read(event.fd, 10) |
| 52 | if s == 'stop\n' { |
| 53 | eprintln('stopping') |
| 54 | return |
| 55 | } |
| 56 | } |
| 57 | else { |
| 58 | // remote connection |
| 59 | if event.kind.has(.peer_hangup) { |
| 60 | notifier.remove(event.fd) or { |
| 61 | eprintln('error removing from notifier: ${err}') |
| 62 | return |
| 63 | } |
| 64 | eprintln('remote disconnected') |
| 65 | } else { |
| 66 | s, _ := os.fd_read(event.fd, 10) |
| 67 | os.fd_write(event.fd, s) |
| 68 | } |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | |