| 1 | // vtest build: present_openssl? |
| 2 | module main |
| 3 | |
| 4 | import os |
| 5 | import net.websocket |
| 6 | import term |
| 7 | |
| 8 | // This client should be compiled an run in different consoles |
| 9 | // it connects to the server who will broadcast your messages |
| 10 | // to all other connected clients |
| 11 | fn main() { |
| 12 | mut ws := start_client()! |
| 13 | defer { |
| 14 | unsafe { |
| 15 | ws.free() |
| 16 | } |
| 17 | } |
| 18 | println(term.green('client ${ws.id} ready')) |
| 19 | println('Write message and enter to send...') |
| 20 | for { |
| 21 | line := os.get_line() |
| 22 | if line == '' { |
| 23 | break |
| 24 | } |
| 25 | ws.write_string(line)! |
| 26 | } |
| 27 | ws.close(1000, 'normal') or { |
| 28 | eprintln(term.red('ws.close err: ${err}')) |
| 29 | exit(1) |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | fn start_client() !&websocket.Client { |
| 34 | mut ws := websocket.new_client('ws://localhost:30000')! |
| 35 | // mut ws := websocket.new_client('wss://echo.websocket.org:443')? |
| 36 | // use on_open_ref if you want to send any reference object |
| 37 | ws.on_open(fn (mut ws websocket.Client) ! { |
| 38 | println(term.green('ws.on_open websocket connected to the server and ready to send messages...')) |
| 39 | }) |
| 40 | // use on_error_ref if you want to send any reference object |
| 41 | ws.on_error(fn (mut ws websocket.Client, err string) ! { |
| 42 | println(term.red('ws.on_error error: ${err}')) |
| 43 | }) |
| 44 | // use on_close_ref if you want to send any reference object |
| 45 | ws.on_close(fn (mut ws websocket.Client, code int, reason string) ! { |
| 46 | println(term.green('ws.on_close the connection to the server successfully closed')) |
| 47 | }) |
| 48 | // on new messages from other clients, display them in blue text |
| 49 | ws.on_message(fn (mut ws websocket.Client, msg &websocket.Message) ! { |
| 50 | if msg.payload.len > 0 { |
| 51 | message := msg.payload.bytestr() |
| 52 | println(term.blue('ws.on_message `${message}`')) |
| 53 | } |
| 54 | }) |
| 55 | |
| 56 | ws.connect() or { |
| 57 | eprintln(term.red('ws.connect error: ${err}')) |
| 58 | return err |
| 59 | } |
| 60 | |
| 61 | spawn ws.listen() // or { println(term.red('error on listen ${err}')) } |
| 62 | return ws |
| 63 | } |
| 64 | |