1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

net.websocket: call close event (#17300)

This commit is contained in:
starryskye 2023-02-13 05:28:41 -07:00 committed by GitHub
parent 16344cfc28
commit 2d3508c872
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 55 additions and 0 deletions

View File

@ -337,6 +337,7 @@ pub fn (mut ws Client) close(code int, message string) ! {
defer { defer {
ws.shutdown_socket() or {} ws.shutdown_socket() or {}
ws.reset_state() or {} ws.reset_state() or {}
ws.send_close_event(code, message)
} }
ws.set_state(.closing) ws.set_state(.closing)
// mut code32 := 0 // mut code32 := 0

View File

@ -8,6 +8,7 @@ struct WebsocketTestResults {
pub mut: pub mut:
nr_messages int nr_messages int
nr_pong_received int nr_pong_received int
nr_closes int
} }
// Do not run these tests everytime, since they are flaky. // Do not run these tests everytime, since they are flaky.
@ -126,3 +127,56 @@ fn ws_test(family net.AddrFamily, uri string) ! {
assert test_results.nr_pong_received >= 2 assert test_results.nr_pong_received >= 2
assert test_results.nr_messages == 2 assert test_results.nr_messages == 2
} }
fn test_on_close_when_server_closing_connection() ! {
port := 30000 + rand.intn(1024) or { 0 }
mut ws := websocket.new_server(.ip, port, '')
ws.on_message(fn (mut cli websocket.Client, msg &websocket.Message) ! {
if msg.opcode == .text_frame {
cli.close(1000, 'closing connection')!
}
})
mut test_results := WebsocketTestResults{}
ws.on_close_ref(fn (mut cli websocket.Client, code int, reason string, mut res WebsocketTestResults) ! {
res.nr_closes++
}, test_results)
spawn ws.listen()
mut client := websocket.new_client('ws://localhost:${port}')!
client.connect()!
spawn client.listen()
time.sleep(1000 * time.millisecond)
client.write_string('a message')!
time.sleep(1000 * time.millisecond)
assert test_results.nr_closes == 1
}
fn test_on_close_when_client_closing_connection() ! {
port := 30000 + rand.intn(1024) or { 0 }
mut ws := websocket.new_server(.ip, port, '')
spawn ws.listen()
mut client := websocket.new_client('ws://localhost:${port}')!
mut test_results := WebsocketTestResults{}
client.on_close_ref(fn (mut cli websocket.Client, code int, reason string, mut res WebsocketTestResults) ! {
res.nr_closes++
}, test_results)
client.connect()!
spawn client.listen()
time.sleep(1000 * time.millisecond)
client.close(1000, 'closing connection')!
time.sleep(1000 * time.millisecond)
assert test_results.nr_closes == 1
}