2021-01-06 17:43:54 +03:00
|
|
|
module main
|
|
|
|
|
|
|
|
import x.websocket
|
|
|
|
import term
|
|
|
|
|
|
|
|
// this server accepts client connections and broadcast all messages to other connected clients
|
|
|
|
fn main() {
|
2021-01-31 17:18:04 +03:00
|
|
|
println('press ctrl-c to quit...')
|
|
|
|
start_server() ?
|
2021-01-06 17:43:54 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
fn start_server() ? {
|
2021-06-13 23:53:38 +03:00
|
|
|
mut s := websocket.new_server(.ip6, 30000, '')
|
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
|
|
|
|
s.on_connect(fn (mut s websocket.ServerClient) ?bool {
|
|
|
|
// 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
|
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
|
|
|
|
s.on_message_ref(fn (mut ws websocket.Client, msg &websocket.Message, mut m websocket.Server) ? {
|
2021-01-31 12:37:32 +03:00
|
|
|
// for _, cli in m.clients {
|
|
|
|
for i, _ in m.clients {
|
|
|
|
mut c := m.clients[i]
|
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)
|
|
|
|
|
|
|
|
s.on_close(fn (mut ws websocket.Client, code int, reason string) ? {
|
|
|
|
println(term.green('client ($ws.id) closed connection'))
|
|
|
|
})
|
2021-01-31 17:18:04 +03:00
|
|
|
s.listen() or { println(term.red('error on server listen: $err')) }
|
2021-01-06 17:43:54 +03:00
|
|
|
unsafe {
|
|
|
|
s.free()
|
|
|
|
}
|
|
|
|
}
|