websocketd: WebSockets the Unix way
(That’s lowercase
websocketd
. And the d’s not a
typo.)
I 🖤 WebSockets, for building real time web apps.
But the server side frameworks are kinda complicated. I wanted something simpler.
The Unix philosophy
Wikipedia says:
Write programs that do one thing and do it well.
Write programs to work together.
Write programs to handle text streams, because that is a universal interface.
Or to put another way, decompose the problem.
websocketd
websocketd
is a small
command line tool that will turn another
command line program into a WebSocket
server. Incoming messages are sent to the
program on stdin
, and any
output on stdout
is sent back
to the browser. Each new WebSocket
connection will span an isolated process
(one instance of the program per
connection). If the WebSocket connection is
closed, the program will be terminated.
That’s it. I’ve been using to for years for some pretty significant projects, and though it’s about time it was open sourced. Thanks to my employer DRW for agreeing to it. It’s written in Go, by the way, as that’s a great fit for standalone CLI tools.
The programs it launches can be written in any language. Super convenient.
10 second tutorial
Let’s create a tiny WebSocket server that counts to ten, pausing between each iteration.
Ok, let’s forget about WebSockets for a while, and just write a simple command line program that does this.
We can do this in any language. For fun, let’s do it in Ruby. Also, we’re just writing to the console - no need for any networking libraries.
#!/usr/bin/ruby
# Count from 1 to 10 with a sleep
1..10).each do |count|
(puts count
sleep(0.5)
end
Run it, you’ll see it counting (with pauses between each number):
$ ruby counter.rb
1
2
3
...
Ok, now let’s make it a WebSocket server:
$ websocketd --port=8080 counter.rb
Listening on ws://localhost:8080/...
And from JavaScript in a web-page:
var ws = new WebSocket('ws://localhost:8080/');
.onmessage = function(event) {
wsconsole.log('Count is: ' + event.data);
; }
That’s it!
Links
Update: Surpassed 10,000 stars on GitHub! 🌟