2020-07-25 23:25:31 +03:00
|
|
|
import websocket
|
|
|
|
import time
|
2020-05-26 13:50:37 +03:00
|
|
|
|
2020-07-25 23:25:31 +03:00
|
|
|
struct Test {
|
|
|
|
mut:
|
|
|
|
connected bool = false
|
2020-07-28 18:48:25 +03:00
|
|
|
sent_messages []string = []
|
|
|
|
received_messages []string = []
|
2020-07-25 23:25:31 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
fn test_ws() {
|
|
|
|
ws_test('ws://echo.websocket.org')
|
|
|
|
ws_test('wss://echo.websocket.org')
|
|
|
|
}
|
|
|
|
|
|
|
|
fn ws_test(uri string) {
|
|
|
|
mut test := Test{}
|
|
|
|
println('connecting to $uri ...')
|
|
|
|
mut ws := websocket.new(uri)
|
|
|
|
ws.subscriber.subscribe_method('on_open', on_open, test)
|
|
|
|
ws.subscriber.subscribe_method('on_message', on_message, test)
|
|
|
|
ws.subscriber.subscribe('on_error', on_error)
|
|
|
|
ws.subscriber.subscribe_method('on_close', on_close, test)
|
|
|
|
ws.connect()
|
|
|
|
go ws.listen()
|
|
|
|
text := ['ws test', '{"vlang": "test0\n192"}']
|
|
|
|
for msg in text {
|
2020-07-28 18:48:25 +03:00
|
|
|
test.sent_messages << msg
|
2020-07-25 23:25:31 +03:00
|
|
|
len := ws.write(msg.str, msg.len, .text_frame)
|
|
|
|
assert msg.len <= len
|
|
|
|
// sleep to give time to recieve response before send a new one
|
|
|
|
time.sleep_ms(100)
|
|
|
|
}
|
|
|
|
// sleep to give time to recieve response before asserts
|
|
|
|
time.sleep_ms(500)
|
|
|
|
|
|
|
|
assert test.connected == true
|
2020-07-28 18:48:25 +03:00
|
|
|
assert test.sent_messages.len == test.received_messages.len
|
|
|
|
for x, msg in test.sent_messages {
|
|
|
|
assert msg == test.received_messages[x]
|
2020-07-25 23:25:31 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-28 18:48:25 +03:00
|
|
|
fn on_open(mut test Test, x voidptr, ws &websocket.Client) {
|
2020-07-25 23:25:31 +03:00
|
|
|
println('websocket opened.')
|
|
|
|
test.connected = true
|
|
|
|
}
|
|
|
|
|
|
|
|
fn on_message(mut test Test, msg &websocket.Message, ws &websocket.Client) {
|
|
|
|
typ := msg.opcode
|
|
|
|
if typ == .text_frame {
|
|
|
|
println('Message: ${cstring_to_vstring(msg.payload)}')
|
2020-07-28 18:48:25 +03:00
|
|
|
test.received_messages << cstring_to_vstring(msg.payload)
|
2020-07-25 23:25:31 +03:00
|
|
|
} else {
|
|
|
|
println('Binary message: $msg')
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-28 18:48:25 +03:00
|
|
|
fn on_close(x, y voidptr, ws &websocket.Client) {
|
2020-07-25 23:25:31 +03:00
|
|
|
println('websocket closed.')
|
|
|
|
}
|
|
|
|
|
2020-07-28 18:48:25 +03:00
|
|
|
fn on_error(x, y voidptr, ws &websocket.Client) {
|
2020-07-25 23:25:31 +03:00
|
|
|
println('we have an error.')
|
|
|
|
assert false
|
2020-05-26 13:50:37 +03:00
|
|
|
}
|