| 1 | import context |
| 2 | import net.websocket |
| 3 | import x.async as xasync |
| 4 | |
| 5 | fn describe_message(msg websocket.Message) !string { |
| 6 | return match msg.opcode { |
| 7 | .text_frame { |
| 8 | 'text:${msg.payload.bytestr()}' |
| 9 | } |
| 10 | .ping { |
| 11 | 'ping' |
| 12 | } |
| 13 | else { |
| 14 | error('unsupported websocket message opcode') |
| 15 | } |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | fn main() { |
| 20 | messages := [ |
| 21 | websocket.Message{ |
| 22 | opcode: .text_frame |
| 23 | payload: 'hello'.bytes() |
| 24 | }, |
| 25 | websocket.Message{ |
| 26 | opcode: .ping |
| 27 | }, |
| 28 | ] |
| 29 | processed := chan string{cap: messages.len} |
| 30 | mut group := xasync.new_group(context.background()) |
| 31 | |
| 32 | for msg in messages { |
| 33 | group.go(fn [msg, processed] (mut ctx context.Context) ! { |
| 34 | done := ctx.done() |
| 35 | select { |
| 36 | _ := <-done { |
| 37 | return ctx.err() |
| 38 | } |
| 39 | else {} |
| 40 | } |
| 41 | processed <- describe_message(msg)! |
| 42 | })! |
| 43 | } |
| 44 | |
| 45 | group.wait()! |
| 46 | for _ in 0 .. messages.len { |
| 47 | println(<-processed) |
| 48 | } |
| 49 | } |
| 50 | |