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

54 lines
1.3 KiB
V
Raw Normal View History

module main
2020-04-26 14:49:31 +03:00
import net.websocket
import time
2020-04-08 22:21:58 +03:00
fn main() {
//URLs working for testing, reply the same sent messages
ws_test('ws://echo.websocket.org')
ws_test('wss://echo.websocket.org')
}
fn ws_test(uri string) {
println('connecting to $uri ...')
mut ws := websocket.new(uri)
2020-04-08 22:21:58 +03:00
ws.subscriber.subscribe('on_open', on_open)
ws.subscriber.subscribe('on_message', on_message)
ws.subscriber.subscribe('on_error', on_error)
ws.subscriber.subscribe('on_close', on_close)
ws.connect()
// Needs another thread, generates an infinite loop for listen
go ws.listen()
for i := 0; i < 10; i++ {
text := 'a'.repeat(i)
println(text)
// Send a text to the server
ws.write(text.str, text.len, .text_frame)
// Only for test purposes, to give time to receive message
time.sleep_ms(100)
}
// Only for test purposes, to give time to receive message
time.sleep_ms(100)
}
fn on_open(ws &websocket.Client, x, y voidptr) {
2020-04-08 22:21:58 +03:00
println('websocket opened.')
}
fn on_message(ws &websocket.Client, msg &websocket.Message, x voidptr) {
2020-05-28 01:38:54 +03:00
typ := msg.opcode
if typ == .text_frame {
println('Message: ${cstring_to_vstring(msg.payload)}')
} else {
println('Binary message: $msg')
}
}
fn on_close(ws &websocket.Client, x, y voidptr) {
2020-04-08 22:21:58 +03:00
println('websocket closed.')
}
fn on_error(ws &websocket.Client, x, y voidptr) {
2020-04-08 22:21:58 +03:00
println('we have an error.')
}