v2 / vlib / x / async / examples / net_websocket / message_pipeline.v
49 lines · 45 sloc · 842 bytes · 15fb60b77ea6073658aa8355b247f2e1ae03b714
Raw
1import context
2import net.websocket
3import x.async as xasync
4
5fn 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
19fn 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