2020-04-08 15:22:31 +03:00
|
|
|
module main
|
|
|
|
|
2020-04-26 14:49:31 +03:00
|
|
|
import net.websocket
|
2020-07-22 17:44:56 +03:00
|
|
|
import time
|
2020-04-08 22:21:58 +03:00
|
|
|
|
|
|
|
fn main() {
|
2020-07-22 17:44:56 +03:00
|
|
|
//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) {
|
2020-07-22 18:42:57 +03:00
|
|
|
println('connecting to $uri ...')
|
2020-07-22 17:44:56 +03:00
|
|
|
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)
|
2020-04-08 20:44:30 +03:00
|
|
|
ws.connect()
|
2020-07-22 17:44:56 +03:00
|
|
|
// 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)
|
2020-04-08 15:22:31 +03:00
|
|
|
}
|
2020-07-22 17:44:56 +03:00
|
|
|
// Only for test purposes, to give time to receive message
|
|
|
|
time.sleep_ms(100)
|
2020-04-08 15:22:31 +03:00
|
|
|
}
|
|
|
|
|
2020-07-22 17:44:56 +03:00
|
|
|
fn on_open(ws &websocket.Client, x, y voidptr) {
|
2020-04-08 22:21:58 +03:00
|
|
|
println('websocket opened.')
|
2020-04-08 15:22:31 +03:00
|
|
|
}
|
|
|
|
|
2020-07-22 17:44:56 +03:00
|
|
|
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 {
|
2020-07-22 17:44:56 +03:00
|
|
|
println('Message: ${cstring_to_vstring(msg.payload)}')
|
2020-04-08 15:22:31 +03:00
|
|
|
} else {
|
2020-07-22 17:44:56 +03:00
|
|
|
println('Binary message: $msg')
|
2020-04-08 15:22:31 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-22 17:44:56 +03:00
|
|
|
fn on_close(ws &websocket.Client, x, y voidptr) {
|
2020-04-08 22:21:58 +03:00
|
|
|
println('websocket closed.')
|
2020-04-08 15:22:31 +03:00
|
|
|
}
|
|
|
|
|
2020-07-22 17:44:56 +03:00
|
|
|
fn on_error(ws &websocket.Client, x, y voidptr) {
|
2020-04-08 22:21:58 +03:00
|
|
|
println('we have an error.')
|
|
|
|
}
|