Websocket Connection
A WebsocketConnection type is not directly constructed by the user. it can exist in two contexts:
Typical SERVER:
using SimpleWebsockets
server = WebsocketServer()
listen(server, :client) do client::WebsocketConnection
# do logic with the `WebsocketConnection`
end
serve(server)Typical CLIENT
using SimpleWebsockets
client = WebsocketClient()
listen(client, :connect) do ws::WebsocketConnection
# do logic with the `WebsocketConnection`
end
open(client, "ws://url.url")WebsocketConnection Methods
SimpleWebsockets.send — Functionsend(ws::WebsocketConnection, data::Union{String, Number, Array{UInt8,1}})Send the given data as a message over the wire.
Base.Broadcast.broadcast — Methodbroadcast(client::WebsocketConnection, data::Union{Array{UInt8,1}, String, Number})send the given data as a message to all connected clients, except the given client.
In a SERVER context, to communicate with all clients on the SERVER, use emit
Only used if the client is in a SERVER context, otherwise NOOP.
SimpleWebsockets.ping — Functionping(ws::WebsocketConnection, data::Union{String, Number})Send data as ping message to the ws peer.
data is limited to 125Bytes, and will automatically be truncated if over this limit.
Base.close — Methodclose(ws::WebsocketConnection [, reasonCode::Int, description::String])Closes a websocket connection.
Sends the close frame to the peer, waits for the response close frame, or times out on closeTimeout before closing the underlying TCP stream.
Optional reasonCode must be a valid rfc6455 code, suitable for sending over the wire.
Defaults: 1000 : "Normal connection closure"
WebsocketConnection Events
WebsocketConnection event callback functions are registered using the listen method.
SimpleWebsockets.listen — Methodlisten(callback::Function, ws::SimpleWebsockets.WebsocketConnection, event::Symbol)Register event callbacks onto a WebsocketConnection. The callback must be a function with exactly one argument.
Valid events are:
- :message
- :pong
- :error
- :close
Example
listen(ws::WebsocketConnection, :message) do message
#...
endTriggered when the TCP stream receives a message
listen(ws::WebsocketConnection, :message) do message::Union{String, Array{UInt8, 1}}
#...
endTriggered when the TCP stream receives a pong response
listen(ws::WebsocketConnection, :pong) do message::Union{String, Array{UInt8, 1}}
#...
endTriggered when an error occurs during data processing
listen(ws::WebsocketConnection, :error) do err::Union{WebsocketError.FrameError, WebsocketError.CallbackError}
# err.msg::String
# err.log::Function > logs the error message with stack trace
endTriggered when the underlying TCP stream has closed
listen(ws::WebsocketConnection, :close) do reason::NamedTuple
# reason.code::Int
# reason.description::String
end