2021-01-06 15:43:54 +01:00
|
|
|
module main
|
|
|
|
|
|
|
|
import os
|
2021-07-03 01:56:00 +02:00
|
|
|
import net.websocket
|
2021-01-06 15:43:54 +01:00
|
|
|
import term
|
|
|
|
|
2021-07-28 21:39:37 +02:00
|
|
|
// This client should be compiled an run in different consoles
|
2021-01-06 15:43:54 +01:00
|
|
|
// it connects to the server who will broadcast your messages
|
|
|
|
// to all other connected clients
|
|
|
|
fn main() {
|
|
|
|
mut ws := start_client() ?
|
|
|
|
println(term.green('client $ws.id ready'))
|
|
|
|
println('Write message and enter to send...')
|
|
|
|
for {
|
2021-01-26 15:43:10 +01:00
|
|
|
line := os.get_line()
|
2021-01-06 15:43:54 +01:00
|
|
|
if line == '' {
|
|
|
|
break
|
|
|
|
}
|
2021-03-20 17:25:51 +01:00
|
|
|
ws.write_string(line) ?
|
2021-01-06 15:43:54 +01:00
|
|
|
}
|
2021-01-26 15:43:10 +01:00
|
|
|
ws.close(1000, 'normal') or { println(term.red('panicing $err')) }
|
2021-01-06 15:43:54 +01:00
|
|
|
unsafe {
|
|
|
|
ws.free()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn start_client() ?&websocket.Client {
|
2021-01-26 15:43:10 +01:00
|
|
|
mut ws := websocket.new_client('ws://localhost:30000') ?
|
2021-01-06 15:43:54 +01:00
|
|
|
// mut ws := websocket.new_client('wss://echo.websocket.org:443')?
|
|
|
|
// use on_open_ref if you want to send any reference object
|
|
|
|
ws.on_open(fn (mut ws websocket.Client) ? {
|
|
|
|
println(term.green('websocket connected to the server and ready to send messages...'))
|
|
|
|
})
|
|
|
|
// use on_error_ref if you want to send any reference object
|
|
|
|
ws.on_error(fn (mut ws websocket.Client, err string) ? {
|
|
|
|
println(term.red('error: $err'))
|
|
|
|
})
|
|
|
|
// use on_close_ref if you want to send any reference object
|
|
|
|
ws.on_close(fn (mut ws websocket.Client, code int, reason string) ? {
|
|
|
|
println(term.green('the connection to the server successfully closed'))
|
|
|
|
})
|
|
|
|
// on new messages from other clients, display them in blue text
|
|
|
|
ws.on_message(fn (mut ws websocket.Client, msg &websocket.Message) ? {
|
|
|
|
if msg.payload.len > 0 {
|
|
|
|
message := msg.payload.bytestr()
|
|
|
|
println(term.blue('$message'))
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2021-01-26 15:43:10 +01:00
|
|
|
ws.connect() or { println(term.red('error on connect: $err')) }
|
|
|
|
|
2021-02-27 09:16:55 +01:00
|
|
|
go ws.listen() // or { println(term.red('error on listen $err')) }
|
2021-01-06 15:43:54 +01:00
|
|
|
return ws
|
2021-01-23 10:25:40 +01:00
|
|
|
}
|