2020-04-08 14:22:31 +02:00
|
|
|
module main
|
|
|
|
|
2020-04-26 13:49:31 +02:00
|
|
|
import net.websocket
|
2020-07-22 16:44:56 +02:00
|
|
|
import time
|
2020-04-08 21:21:58 +02:00
|
|
|
|
|
|
|
fn main() {
|
2020-07-22 16:44:56 +02: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 17:42:57 +02:00
|
|
|
println('connecting to $uri ...')
|
2020-07-22 16:44:56 +02:00
|
|
|
mut ws := websocket.new(uri)
|
2020-04-08 21:21:58 +02: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 19:44:30 +02:00
|
|
|
ws.connect()
|
2020-07-22 16:44:56 +02: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 14:22:31 +02:00
|
|
|
}
|
2020-07-22 16:44:56 +02:00
|
|
|
// Only for test purposes, to give time to receive message
|
|
|
|
time.sleep_ms(100)
|
2020-04-08 14:22:31 +02:00
|
|
|
}
|
|
|
|
|
2020-07-22 16:44:56 +02:00
|
|
|
fn on_open(ws &websocket.Client, x, y voidptr) {
|
2020-04-08 21:21:58 +02:00
|
|
|
println('websocket opened.')
|
2020-04-08 14:22:31 +02:00
|
|
|
}
|
|
|
|
|
2020-07-22 16:44:56 +02:00
|
|
|
fn on_message(ws &websocket.Client, msg &websocket.Message, x voidptr) {
|
2020-05-28 00:38:54 +02:00
|
|
|
typ := msg.opcode
|
|
|
|
if typ == .text_frame {
|
2020-07-22 16:44:56 +02:00
|
|
|
println('Message: ${cstring_to_vstring(msg.payload)}')
|
2020-04-08 14:22:31 +02:00
|
|
|
} else {
|
2020-07-22 16:44:56 +02:00
|
|
|
println('Binary message: $msg')
|
2020-04-08 14:22:31 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-22 16:44:56 +02:00
|
|
|
fn on_close(ws &websocket.Client, x, y voidptr) {
|
2020-04-08 21:21:58 +02:00
|
|
|
println('websocket closed.')
|
2020-04-08 14:22:31 +02:00
|
|
|
}
|
|
|
|
|
2020-07-22 16:44:56 +02:00
|
|
|
fn on_error(ws &websocket.Client, x, y voidptr) {
|
2020-04-08 21:21:58 +02:00
|
|
|
println('we have an error.')
|
|
|
|
}
|