2021-01-06 17:43:54 +03:00
|
|
|
module main
|
|
|
|
|
2021-07-03 02:56:00 +03:00
|
|
|
import net.websocket
|
2021-01-06 17:43:54 +03:00
|
|
|
import term
|
|
|
|
|
2023-01-15 15:48:52 +03:00
|
|
|
fn slog(message string) {
|
|
|
|
eprintln(term.colorize(term.bright_yellow, message))
|
|
|
|
}
|
|
|
|
|
2021-01-06 17:43:54 +03:00
|
|
|
// this server accepts client connections and broadcast all messages to other connected clients
|
|
|
|
fn main() {
|
2023-01-15 15:48:52 +03:00
|
|
|
eprintln('press ctrl-c to quit...')
|
2022-10-16 09:28:57 +03:00
|
|
|
start_server()!
|
2021-01-06 17:43:54 +03:00
|
|
|
}
|
|
|
|
|
2022-10-16 09:28:57 +03:00
|
|
|
fn start_server() ! {
|
2023-01-15 15:48:52 +03:00
|
|
|
slog('start_server')
|
2021-06-13 23:53:38 +03:00
|
|
|
mut s := websocket.new_server(.ip6, 30000, '')
|
2023-01-15 15:48:52 +03:00
|
|
|
defer {
|
|
|
|
unsafe {
|
|
|
|
s.free()
|
|
|
|
}
|
|
|
|
}
|
2021-01-06 17:43:54 +03:00
|
|
|
// Make that in execution test time give time to execute at least one time
|
|
|
|
s.ping_interval = 100
|
2022-10-16 09:28:57 +03:00
|
|
|
s.on_connect(fn (mut s websocket.ServerClient) !bool {
|
2023-01-15 15:48:52 +03:00
|
|
|
slog('s.on_connect')
|
2021-01-06 17:43:54 +03:00
|
|
|
// Here you can look att the client info and accept or not accept
|
|
|
|
// just returning a true/false
|
|
|
|
if s.resource_name != '/' {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
2022-10-16 09:28:57 +03:00
|
|
|
})!
|
2021-01-31 17:18:04 +03:00
|
|
|
|
2021-01-06 17:43:54 +03:00
|
|
|
// on_message_ref, broadcast all incoming messages to all clients except the one sent it
|
2022-10-16 09:28:57 +03:00
|
|
|
s.on_message_ref(fn (mut ws websocket.Client, msg &websocket.Message, mut m websocket.Server) ! {
|
2023-01-15 15:48:52 +03:00
|
|
|
slog('s.on_message_ref')
|
2021-01-31 12:37:32 +03:00
|
|
|
// for _, cli in m.clients {
|
|
|
|
for i, _ in m.clients {
|
2023-01-16 00:19:16 +03:00
|
|
|
mut c := m.clients[i] or { continue }
|
2021-01-31 17:18:04 +03:00
|
|
|
if c.client.state == .open && c.client.id != ws.id {
|
2021-03-01 02:18:14 +03:00
|
|
|
c.client.write(msg.payload, websocket.OPCode.text_frame) or { panic(err) }
|
2021-01-06 17:43:54 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}, s)
|
|
|
|
|
2022-10-16 09:28:57 +03:00
|
|
|
s.on_close(fn (mut ws websocket.Client, code int, reason string) ! {
|
2023-01-15 15:48:52 +03:00
|
|
|
slog('s.on_close')
|
2022-11-15 16:53:13 +03:00
|
|
|
println(term.green('client (${ws.id}) closed connection'))
|
2021-01-06 17:43:54 +03:00
|
|
|
})
|
2023-01-15 15:48:52 +03:00
|
|
|
|
2022-11-15 16:53:13 +03:00
|
|
|
s.listen() or { println(term.red('error on server listen: ${err}')) }
|
2023-01-15 15:48:52 +03:00
|
|
|
slog('s.listen done')
|
2021-01-06 17:43:54 +03:00
|
|
|
}
|