websocket(n)
π websocket(n) β websocket client and server π
okay so bestie, welcome to the websocket page, this is part 1 of 3 so like, buckle up π
β¨ NAME β¨
websocket β Tcl implementation of the websocket protocol π¦
β¨ SYNOPSIS β¨
package require Tcl 8.6 9
package require http 2.7
package require logger
package require sha1
package require base64
package require websocket ?1.6?
::websocket::open url handler ?options?
::websocket::send sock type ?msg? ?final?
::websocket::server sock
::websocket::live sock path cb ?proto?
::websocket::test srvSock cliSock path ?hdrs? ?qry?
::websocket::upgrade sock
::websocket::takeover sock handler ?server?
::websocket::conninfo sock what
::websocket::find ?host? ?port?
::websocket::configure sock args
::websocket::loglevel ?loglvl?
::websocket::close sock ?code? ?reason?
β¨ DESCRIPTION β¨
NOTE: THIS DOCUMENTATION IS WORK IN PROGRESS... π
The websocket library is a pure Tcl implementation of the WebSocket specification, and it covers the needs of both clients and servers, like it's giving versatility fr fr π
Websockets provide a way to upgrade a regular HTTP connection into a long-lived and continuous binary or text communication between the client and the server. So no more awkward reconnecting every five seconds, it's giving main character energy β¨
The library offers a high-level interface to receive and send data as specified in RFC 6455 (v. 13 of the protocol), relieving callers from all necessary protocol framing and reassembly. It implements the ping facility specified by the standard, together with levers to control it. Pings are server-driven and ensure the liveness of the connection across home (NAT) networks. π«Ά
The library also has a number of introspection facilities to inquire about the current state of the connection, and to receive notifications of incoming pings, if necessary. And finally, the library contains a number of helper procedures to facilitate the upgrading handshaking in existing web servers. πΈ
π§ the central one: takeover
Central to the library is the procedure websocket::takeover, which will take over a regular socket and treat it as a WebSocket, thus performing all necessary protocol framing, packetisation and reassembly in servers and clients. π
The procedure also takes a handler, a command that will be called back each time a (possibly reassembled) packet from the remote end is ready for delivery at the original caller.
While exported by the package, the command websocket::takeover is seldom called in applications, since the package provides other commands that are specifically tuned for the needs of clients and servers. So like, it's iconic but you probably won't be texting it directly, iykyk π
π clients, bestie
Typically, clients will open a connection to a remote server by providing a WebSocket URL (ws: or wss: schemes) and the handler described above to the command websocket::open.
The opening procedure is a wrapper around the latest http::geturl implementations: it arranges to keep the socket created within the http library opened for reuse, but confiscates it from its (internal) map of known sockets for its own use. lowkey feral but okay π
π servers, also bestie
Servers will start by registering themselves through the command ::websocket::server and a number of handlers for paths using the command ::websocket::live.
Then for each incoming client connection, they should test the incoming request to detect if it is an upgrade request using ::websocket::test and perform the final handshake to place the socket connection under the control of the websocket library and its central procedure using ::websocket::upgrade. β¨
π₯ everything else
Apart from these main commands, the package provides a number of commands for introspection and basic operations on the websockets that it has under its control. π¦
As WebSockets connections are long-lived, most remaining communication with the library will be by way of callbacks, i.e. commands that are triggered whenever important events within the library have occur, but mostly whenever data has been received on a WebSocket. No cap, it's a callback kind of lifestyle. π
β¨ CALLBACKS β¨
A number of commands of the library take a handler command as an argument, a command which will be called back upon reception of data, but also upon important events within the library or events resulting from control messages sent by the remote end.
For each callback being performed, the following arguments will be appended: π
sockβ the identifier of the WebSocket, as returned for example by::websocket::opentypeβ a textual type describing the event or message content, can be one of the following:textβ complete text message β¨binaryβ complete binary message πpingβ incoming ping message πpongβ response to incoming ping message πconnectβ notification of successful connection to server πdisconnectβ disconnection from remote end πcloseβ pending closure of connection πtimeoutβ notification of connection timeout πerrorβ notification of error condition π¨
msgβ will contain the data of the message, whenever this is relevant, i.e. when thetypeistext,binary,pingorpongand whenever there is data available.
okay that's the whole first chunk, stay tuned because there is MORE π
π API π
okay bestie this is the good part, this is where the actual commands live π«Ά
::websocket::open url handler ?options?
Client side, opening time, let's gooo. This is the one you use in clients to open a WebSocket to a remote websocket-enabled HTTP server. The url you pass has to start with ws: or wss: β those are literally the WebSockets counterpart of http: and https:, no cap. The handler is a command that gets called back on data reception or whenever important events occur during the life of the websocket (the whole callback situation is described back in the Callbacks section, go peek if you skipped it π).
::websocket::open will return a socket, and that socket is doing double duty: it's both the identifier of the websocket and of the physical low-level socket to the server. You can feed it into a bunch of other commands for introspection or for controlling the behaviour of the library. Under the hood it's basically a wrapper around ::http::geturl, so it offers mostly the same set of dash-led options as ::http::geturl does. What I'm listing below are the options that differ from ::http::geturl and which are specific to the WebSocket library:
-headersβ supported β¨ just know that a number of headers get automatically added internally in the library so it can handshake the upgrading of the socket from a regular HTTP socket to a WebSocket with the server.-validateβ not supported, it just has no real point for WebSockets.-handlerβ used internally by the websocket library, so you cannot use it, sorry bestie π-commandβ also used internally by the websocket library, also cannot be used.-protocolβ this one specifies a list of application protocols to handshake with the server. These protocols might help the server triggering application specific features π. Heads up though: thehttp::geturloption-protocolis used internally by the websocket library and cannot be used.-timeoutβ supported, but it's implemented as part of the library so that a number of finalising cleanups can happen.
::websocket::send sock type ?msg? ?final?
Send a fragment or a control message to the remote end of the WebSocket identified by sock. The type of the message can either be an integer according to the specification, or β preferably π
β one of these case insensitive strings: "text", "binary" or "ping". The content of the message to send lives in msg, and message fragmentation is made possible by setting the argument final to non-true, knowing that the type of each fragment has then to be the same. The command returns the number of bytes that were effectively sent, or -1 on errors. Serious errors β like when sock does not identify a known WebSocket, or when the connection is not stable yet β will generate errors that must be catched. fr fr, wrap that in a catch.
::websocket::server sock
This one registers the (accept) socket sock as the identifier fo an HTTP server that is capable of doing WebSockets. Paths onto which this server will listen for incoming connections should be declared using ::websocket::live. π¦
::websocket::live sock path cb ?proto?
This procedure registers callbacks that will be performed on a WebSocket compliant server registered with ::websocket::server whenever a client connects to a matching path and protocol. So: sock is the listening socket of the websocket compliant server declared using ::websocket::server. path is a glob-style path to match in client request, whenever this will occur. cb is the command to callback (see Callbacks). And proto is a glob-style protocol name matcher. π
::websocket::test srvSock cliSock path ?hdrs? ?qry?
This procedure will test if the connection from an incoming client on socket cliSock and on the path path is the opening of a WebSocket stream within a known server srvSock. Important vibe check: the incoming request is not upgraded at once β instead a (temporary) context for the incoming connection is created. That's on purpose, because it lets server code perform a number of actions, if necessary, before the WebSocket stream connection goes live. The text is made by analysing the content of the headers hdrs, which should contain a dictionary list of the HTTP headers of the incoming client connection. The command will return 1 if this is an incoming WebSocket upgrade request and 0 otherwise. π«Ά
::websocket::upgrade sock
Upgrade the socket sock that had been deemed by ::websocket::test to be a WebSocket connection request to a true WebSocket as recognised by this library. As a result, the necessary connection handshake will be sent to the client, and the command will arrange for relevant callbacks to be made during the life of the WebSocket, notably using the specifications described by ::websocket::live. glow up complete β¨
::websocket::takeover sock handler ?server?
Take over the existing opened socket sock to implement sending and receiving WebSocket framing on top of the socket. The procedure arranges for handler to be called back whenever messages, control messages or other important internal events are received or occured. server defaults to 0 and can be set to 1 (or a boolean that evaluates to true) to specify that this is a WebSocket within a server. Apart from specificities in the protocol, servers should ping their clients at regular intervals in order to keep the connection opened at all time β°. When server is set to true, the library will arrange to send these pings automatically. iconic, honestly.
::websocket::conninfo sock what
Provides callers with some introspection facilities in order to get some semi-internal information about an existing websocket connection. Depending on the value of the what argument, the procedure returns the following piece of information:
peernameβ Name (preferred) or IP of remote end.socknameornameβ Name or IP of local end.closedβ1if the connection is closed,0otherwiseclientβ1if the connection is a client websocket,0otherwiseserverβ1if the connection is a server websocket,0otherwisetypeβserverif the connection is a server websocket,clientotherwise.handlerβ The handler command associated to the websocketstateβ The state of the websocket, which can be one of:CONNECTINGβ Connection to remote end is in progress.CONNECTEDβ Connection is connected to remote end.CLOSEDβ Connection is closed.
::websocket::find ?host? ?port?
Look among existing websocket connections for the ones that match the hostname and port number filters passed as parameters. This lookup takes the remote end into account, and the host argument is matched both against the hostname (whenever available) and the IP address of the remote end. Both the host and port arguments are glob-style string matching filters and default to *, i.e. will match any host and/or port number. π
::websocket::configure sock args
This command takes a number of dash-led options (and their values) to configure the behaviour of an existing websocket connection. The recognised options are the following (they can be shortened to the lowest common denominator):
-keepaliveβ is the number of seconds between each keepalive pings being sent along the connection. A zero or negative number will effectively turn off the feature. In servers,-keepalivedefaults to 30 seconds, and in clients, no pings are initiated.-pingβ is the text that is used during the automated pings. This text defaults to the empty string, leading to an empty ping.
::websocket::loglevel ?loglvl?
Set or query the log level of the library, which defaults to error. Logging is built on top of the logger module, and the library makes use of the following levels: debug, info, notice, warn and error. When called with no argument, this procedure will simply return the current log level. Otherwise loglvl should contain the desired log level. π
::websocket::close sock ?code? ?reason?
Gracefully close a websocket that was directly or indirectly passed to ::websocket::takeover. The procedure will optionally send the code and describing reason as part of the closure handshake. Good defaults are provided, so that reasons for a number of known codes will be sent back. Only the first 125 characters of a reason string will be kept and sent as part of the handshake. The known codes are:
1000β Normal closure (the default code when none provided).1001β Endpoint going away1002β Protocol Error1003β Received incompatible data type1006β Abnormal closure1007β Received data not consistent with type1008β Policy violation1009β Received message too big1010β Missing extension1011β Unexpected condition1015β TLS handshake error
not me realising there's still more of this page coming π stay tuned bestie, we're not done yet π
π¬ EXAMPLES β¨
okay bestie here's a whole lil client script, she's cute, she works π«Ά
This example is a client that opens a websocket connection to an echo service, waits 400ms so we know the connection is actually, truly established, and then sends one single textual message that the echo service should bounce right back at us. π
Real talk though: a real-life example would probably use the connect callback to know when the connection to the remote server has been established, and would only send data at that moment. This one's just out here vibing with a timer. Then, finally, the script closes the connection. periodt.
package require websocket
::websocket::loglevel debug
proc handler { sock type msg } {
switch -glob -nocase -- $type {
co* {
puts "Connected on $sock"
}
te* {
puts "RECEIVED: $msg"
}
cl* -
dis* {
}
}
}
proc test { sock } {
puts "[::websocket::conninfo $sock type] from [::websocket::conninfo $sock sockname] to [::websocket::conninfo $sock peername]"
::websocket::send $sock text "Testing, testing..."
after 2000 ::websocket::close $sock
}
set sock [::websocket::open ws://ws.ifelse.io/ handler]
after 400 test $sock
vwait forever
and if you want the other side of the story?? Example code for a websocket server is provided in the Tcllib directory "examples/websocket". go look, it's giving main character energy π§
π TLS SECURITY CONSIDERATIONS π
bestie this part is important, so like, pay attention π
This package uses the TLS package to handle the security for https urls and other socket connections.
Policy decisions β like the set of protocols to support and which ciphers to use β are not the responsibility of TLS, and honestly not of this package either. Nope. Those decisions belong to whichever application is using the package, and they're likely influenced by the set of servers that application is gonna talk to as well. iykyk.
For example: in light of the recent POODLE attack [http://googleonlinesecurity.blogspot.co.uk/2014/10/this-poodle-bites-exploiting-ssl-30.html] discovered by Google, many servers will disable support for the SSLv3 protocol. To handle that change, the applications using TLS must be patched β not this package, and not TLS itself. And such a patch may be as simple as generally activating tls1 support, as shown in the example below. π
package require tls
tls::init -tls1 1 ;# forcibly activate support for the TLS1 protocol
... your own application code ...
π BUGS, IDEAS, FEEDBACK π
ngl, this document and the package it describes will undoubtedly contain bugs and other problems. it's giving humbling. π
Please report such in the category websocket of the Tcllib Trackers [http://core.tcl.tk/tcllib/reportlist]. And please also report any ideas for enhancements you may have for either the package and/or the documentation. we wanna hear it fr fr π«Ά
When proposing code changes, please provide unified diffs, i.e the output of diff -u.
Note further that attachments are strongly preferred over inlined patches. Attachments can be made by going to the Edit form of the ticket immediately after its creation, and then using the left-most button in the secondary navigation bar. don't skip this step bestie, it's lowkey the whole vibe πΈ
π SEE ALSO
http
π KEYWORDS
http, internet, net, rfc 6455 β¨
ποΈ CATEGORY
Networking π
and that's the whole page, we did it!! π this one came from tcllib, version 1.6, and it's websocket(n) β the date field up there is being all mysterious and blank, but the version is right there and she's iconic. slay, go build something, bye bestie ππ¦
π¦ where this page comes from
- fedora 43: tcllib 2.0-3.fc43 Β· TCL
- fedora 44: tcllib 2.0-4.fc44 Β· TCL
- nixos 26.05: tcllib 2.0
- nixpkgs unstable: tcllib 2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms