examples: improve the output of the websocket examples

This commit is contained in:
Delyan Angelov 2023-01-15 14:48:52 +02:00
parent 634f596d27
commit 7f3531077d
No known key found for this signature in database
GPG key ID: 66886C0F12D595ED
3 changed files with 93 additions and 29 deletions

View file

@ -3,17 +3,28 @@ module main
import net.websocket
import term
fn slog(message string) {
eprintln(term.colorize(term.bright_yellow, message))
}
// this server accepts client connections and broadcast all messages to other connected clients
fn main() {
println('press ctrl-c to quit...')
eprintln('press ctrl-c to quit...')
start_server()!
}
fn start_server() ! {
slog('start_server')
mut s := websocket.new_server(.ip6, 30000, '')
defer {
unsafe {
s.free()
}
}
// Make that in execution test time give time to execute at least one time
s.ping_interval = 100
s.on_connect(fn (mut s websocket.ServerClient) !bool {
slog('s.on_connect')
// Here you can look att the client info and accept or not accept
// just returning a true/false
if s.resource_name != '/' {
@ -24,6 +35,7 @@ fn start_server() ! {
// on_message_ref, broadcast all incoming messages to all clients except the one sent it
s.on_message_ref(fn (mut ws websocket.Client, msg &websocket.Message, mut m websocket.Server) ! {
slog('s.on_message_ref')
// for _, cli in m.clients {
for i, _ in m.clients {
mut c := m.clients[i]
@ -34,10 +46,10 @@ fn start_server() ! {
}, s)
s.on_close(fn (mut ws websocket.Client, code int, reason string) ! {
slog('s.on_close')
println(term.green('client (${ws.id}) closed connection'))
})
s.listen() or { println(term.red('error on server listen: ${err}')) }
unsafe {
s.free()
}
slog('s.listen done')
}