mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
websocket: minor improvements in the server example
This commit is contained in:
parent
9638013203
commit
c91f7746fd
@ -1,14 +1,12 @@
|
|||||||
module main
|
module main
|
||||||
|
|
||||||
import os
|
|
||||||
import x.websocket
|
import x.websocket
|
||||||
import term
|
import term
|
||||||
|
|
||||||
// this server accepts client connections and broadcast all messages to other connected clients
|
// this server accepts client connections and broadcast all messages to other connected clients
|
||||||
fn main() {
|
fn main() {
|
||||||
go start_server()
|
println('press ctrl-c to quit...')
|
||||||
println('press enter to quit...')
|
start_server() ?
|
||||||
os.get_line()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn start_server() ? {
|
fn start_server() ? {
|
||||||
@ -22,17 +20,15 @@ fn start_server() ? {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
})?
|
}) ?
|
||||||
|
|
||||||
// on_message_ref, broadcast all incoming messages to all clients except the one sent it
|
// 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) ? {
|
s.on_message_ref(fn (mut ws websocket.Client, msg &websocket.Message, mut m websocket.Server) ? {
|
||||||
// for _, cli in m.clients {
|
// for _, cli in m.clients {
|
||||||
for i, _ in m.clients {
|
for i, _ in m.clients {
|
||||||
mut c := m.clients[i]
|
mut c := m.clients[i]
|
||||||
if c.client.state == .open && c.client.id != ws.id {
|
if c.client.state == .open && c.client.id != ws.id {
|
||||||
c.client.write(msg.payload, websocket.OPCode.text_frame) or {
|
c.client.write(msg.payload, websocket.OPCode.text_frame) or { panic(err) }
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, s)
|
}, s)
|
||||||
@ -40,9 +36,7 @@ fn start_server() ? {
|
|||||||
s.on_close(fn (mut ws websocket.Client, code int, reason string) ? {
|
s.on_close(fn (mut ws websocket.Client, code int, reason string) ? {
|
||||||
println(term.green('client ($ws.id) closed connection'))
|
println(term.green('client ($ws.id) closed connection'))
|
||||||
})
|
})
|
||||||
s.listen() or {
|
s.listen() or { println(term.red('error on server listen: $err')) }
|
||||||
println(term.red('error on server listen: $err'))
|
|
||||||
}
|
|
||||||
unsafe {
|
unsafe {
|
||||||
s.free()
|
s.free()
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user