Skip to content

net.websocket #

Websocket callbacks

Websocket event callbacks have result signatures, such as fn (mut client websocket.Client, message &websocket.Message) !. Callbacks that return void can also be registered: returning normally is treated as success. The C backend adapts their return value so the listener receives a valid successful result.

For callbacks registered with on_message_ref, the last voidptr argument is the original reference passed at registration. Cast it back to its concrete reference type in an unsafe block, and keep the referenced object alive while the callback can run. Such a reference can be forwarded as mut unsafe { &Context(ctx) } to a function taking mut context &Context.

A server's on_connect callback runs before its handshake response is written. Use on_attached or on_attached_ref to push frames after the handshake response has been written and the client's callbacks have been registered.

fn new_client #

fn new_client(address string, opt ClientOpt) !&Client

new_client instance a new websocket client

fn new_server #

fn new_server(family net.AddrFamily, port int, route string, opt ServerOpt) &Server

new_server instance a new websocket server on provided port and route

type AcceptClientFn #

type AcceptClientFn = fn (mut c ServerClient) !bool

type ServerAttachedFn #

type ServerAttachedFn = fn (mut c ServerClient) !

type ServerAttachedFn2 #

type ServerAttachedFn2 = fn (mut c ServerClient, v voidptr) !

type SocketCloseFn #

type SocketCloseFn = fn (mut c Client, code int, reason string) !

type SocketCloseFn2 #

type SocketCloseFn2 = fn (mut c Client, code int, reason string, v voidptr) !

type SocketErrorFn #

type SocketErrorFn = fn (mut c Client, err string) !

type SocketErrorFn2 #

type SocketErrorFn2 = fn (mut c Client, err string, v voidptr) !

type SocketMessageFn #

type SocketMessageFn = fn (mut c Client, msg &Message) !

type SocketMessageFn2 #

type SocketMessageFn2 = fn (mut c Client, msg &Message, v voidptr) !

type SocketOpenFn #

type SocketOpenFn = fn (mut c Client) !

type SocketOpenFn2 #

type SocketOpenFn2 = fn (mut c Client, v voidptr) !

fn (Uri) str #

fn (u Uri) str() string

str returns the string representation of the Uri

enum OPCode #

enum OPCode {
	continuation = 0x00
	text_frame   = 0x01
	binary_frame = 0x02
	close        = 0x08
	ping         = 0x09
	pong         = 0x0A
}

OPCode represents the supported websocket frame types

enum State #

enum State {
	connecting = 0
	open
	closing
	closed
}

State represents the state of the websocket connection.

struct Client #

struct Client {
	is_server bool
mut:
	ssl_conn          &ssl.SSLConn = unsafe { nil } // secure connection used when wss is used
	proxy_url         string
	flags             []Flag                // flags used in handshake
	fragments         []Fragment            // current fragments
	message_callbacks []MessageEventHandler // all callbacks on_message
	error_callbacks   []ErrorEventHandler   // all callbacks on_error
	open_callbacks    []OpenEventHandler    // all callbacks on_open
	close_callbacks   []CloseEventHandler   // all callbacks on_close
pub:
	is_ssl        bool   // true if secure socket is used
	uri           Uri    // uri of current connection
	id            string // unique id of client
	read_timeout  i64
	write_timeout i64
pub mut:
	header            http.Header // headers that will be passed when connecting
	conn              &net.TcpConn = unsafe { nil } // underlying TCP socket connection
	nonce_size        int          = 16           // size of nounce used for masking
	panic_on_callback bool               // set to true of callbacks can panic
	client_state      shared ClientState // current state of connection
	// logger used to log messages
	logger        &log.Logger = default_logger
	resource_name string // name of current resource
	last_pong_ut  i64    // last time in unix time we got a pong message
}

Client represents websocket client

fn (Client) on_message #

fn (mut ws Client) on_message(fun SocketMessageFn)

on_message registers a callback on new messages

fn (Client) on_message_ref #

fn (mut ws Client) on_message_ref(fun SocketMessageFn2, ref voidptr)

on_message_ref registers a callback on new messages and provides a reference object

fn (Client) on_error #

fn (mut ws Client) on_error(fun SocketErrorFn)

on_error registers a callback on errors

fn (Client) on_error_ref #

fn (mut ws Client) on_error_ref(fun SocketErrorFn2, ref voidptr)

on_error_ref registers a callback on errors and provides a reference object

fn (Client) on_open #

fn (mut ws Client) on_open(fun SocketOpenFn)

on_open registers a callback on successful opening the websocket

fn (Client) on_open_ref #

fn (mut ws Client) on_open_ref(fun SocketOpenFn2, ref voidptr)

on_open_ref registers a callback on successful opening the websocket and provides a reference object

fn (Client) on_close #

fn (mut ws Client) on_close(fun SocketCloseFn)

on_close registers a callback on closed socket

fn (Client) on_close_ref #

fn (mut ws Client) on_close_ref(fun SocketCloseFn2, ref voidptr)

on_close_ref registers a callback on closed socket and provides a reference object

fn (Client) validate_frame #

fn (mut ws Client) validate_frame(frame &Frame) !

validate_client validates client frame rules from RFC6455

fn (Client) read_next_message #

fn (mut ws Client) read_next_message() !Message

read_next_message reads 1 to n frames to compose a message

fn (Client) parse_frame_header #

fn (mut ws Client) parse_frame_header() !Frame

parse_frame_header parses next message by decoding the incoming frames

fn (Client) connect #

fn (mut ws Client) connect() !

connect connects to remote websocket server

fn (Client) listen #

fn (mut ws Client) listen() !

listen listens and processes incoming messages

fn (Client) ping #

fn (mut ws Client) ping() !

ping sends ping message to server

fn (Client) pong #

fn (mut ws Client) pong() !

pong sends pong message to server,

fn (Client) write_ptr #

fn (mut ws Client) write_ptr(bytes &u8, payload_len int, code OPCode) !int

write_ptr writes len bytes provided a byteptr with a websocket messagetype

fn (Client) write #

fn (mut ws Client) write(bytes []u8, code OPCode) !int

write writes a byte array with a websocket messagetype to socket

fn (Client) write_string #

fn (mut ws Client) write_string(str string) !int

write_str, writes a string with a websocket texttype to socket

fn (Client) close #

fn (mut ws Client) close(code int, message string) !

close closes the websocket connection

fn (Client) set_state #

fn (mut ws Client) set_state(state State)

set_state sets current state of the websocket connection

fn (Client) get_state #

fn (ws &Client) get_state() State

get_state return the current state of the websocket connection

fn (Client) reset_state #

fn (mut ws Client) reset_state() !

reset_state resets the websocket and initialize default settings

fn (Client) free #

fn (c &Client) free()

free handles manual free memory of Client struct

struct ClientOpt #

@[params]
struct ClientOpt {
pub:
	read_timeout  i64         = net.infinite_timeout
	write_timeout i64         = 30 * time.second
	logger        &log.Logger = default_logger
	proxy_url     string // optional proxy URL used to open the websocket TCP tunnel
}

struct ClientState #

struct ClientState {
pub mut:
	state State = .closed // current state of connection
}

struct Message #

struct Message {
pub:
	opcode  OPCode // websocket frame type of this message
	payload []u8   // payload of the message
}

Message represents a whole message combined from 1 to n frames

fn (Message) free #

fn (m &Message) free()

free handles manual free memory of Message struct

struct Server #

struct Server {
mut:
	logger                  &log.Logger      = default_logger
	ls                      &net.TcpListener = unsafe { nil } // listener used to get incoming connection to socket
	accept_client_callbacks []AcceptClientFn // accept client callback functions
	attached_callbacks      []AttachedEventHandler
	message_callbacks       []MessageEventHandler // new message callback functions
	close_callbacks         []CloseEventHandler   // close message callback functions
pub:
	family net.AddrFamily = .ip
	port   int  // port used as listen to incoming connections
	is_ssl bool // true if secure connection (not supported yet on server)
pub mut:
	server_state shared ServerState
}

Server represents a websocket server connection

fn (Server) on_connect #

fn (mut s Server) on_connect(fun AcceptClientFn) !

on_connect registers a callback when client connects to the server

fn (Server) on_message #

fn (mut s Server) on_message(fun SocketMessageFn)

on_message registers a callback on new messages

fn (Server) on_message_ref #

fn (mut s Server) on_message_ref(fun SocketMessageFn2, ref voidptr)

on_message_ref registers a callback on new messages and provides a reference object

fn (Server) on_close #

fn (mut s Server) on_close(fun SocketCloseFn)

on_close registers a callback on closed socket

fn (Server) on_close_ref #

fn (mut s Server) on_close_ref(fun SocketCloseFn2, ref voidptr)

on_close_ref registers a callback on closed socket and provides a reference object

fn (Server) on_attached #

fn (mut s Server) on_attached(fun ServerAttachedFn)

on_attached registers a callback after a client has been attached to the server, the handshake response has been written, and callbacks are set up, but before the blocking listen loop begins.

fn (Server) on_attached_ref #

fn (mut s Server) on_attached_ref(fun ServerAttachedFn2, ref voidptr)

on_attached_ref registers a callback after a client has been attached to the server and provides a reference object.

fn (Server) set_ping_interval #

fn (mut s Server) set_ping_interval(seconds int)

set_ping_interval sets the interval that the server will send ping messages to clients

fn (Server) get_ping_interval #

fn (mut s Server) get_ping_interval() int

get_ping_interval return the interval that the server will send ping messages to clients

fn (Server) listen #

fn (mut s Server) listen() !

listen start listen and process to incoming connections from websocket clients

fn (Server) handle_handshake #

fn (mut s Server) handle_handshake(mut conn net.TcpConn, key string) !&ServerClient

handle_handshake use an existing connection to respond to the handshake for a given key

fn (Server) set_state #

fn (mut s Server) set_state(state State)

set_state sets current state in a thread safe way

fn (Server) get_state #

fn (s &Server) get_state() State

get_state return current state in a thread safe way

fn (Server) free #

fn (mut s Server) free()

free manages manual free of memory for Server instance

struct ServerClient #

struct ServerClient {
pub:
	resource_name string // resource that the client access
	client_key    string // unique key of client
pub mut:
	server &Server = unsafe { nil }
	client &Client = unsafe { nil }
}

ServerClient represents a connected client

struct ServerOpt #

@[params]
struct ServerOpt {
pub:
	logger &log.Logger = default_logger
}

struct ServerState #

struct ServerState {
mut:
	ping_interval int   = 30      // interval for sending ping to clients (seconds)
	state         State = .closed // current state of connection
pub mut:
	clients map[string]&ServerClient // clients connected to this server
}