Echo websocket server using websocketd – as if by magic!

I stum­bled across this lit­tle gem the oth­er day – web­sock­etd – which turns any­thing that takes stan­dard-in and stan­dard-out into a web­sock­et serv­er!

To build a dead sim­ple echo serv­er, fol­low these steps:

  1. fol­low the down­load instruc­tions here (don’t for­get to add it to your PATH)
  2. cre­ate a new con­sole appli­ca­tion in Visu­al Stu­dio (let’s call the con­sole app EchoServ­er), some­thing like this will suf­fice:

  1. run this in com­mand line:

and voila!


Since we enabled the dev con­sole with the dev­con­sole flag we can now go to http://localhost:8080 in the brows­er and test out our echo web­sock­et serv­er inter­ac­tive­ly:


pret­ty sweet, right?


One thing to keep in mind though before you con­sid­er web­sock­etd for any seri­ous devel­op­ment work, is its imple­men­ta­tion details. Based on this para­graph from its project page:

Upon start­up, websocketd will start a Web­Sock­et serv­er on a spec­i­fied port, and lis­ten for con­nec­tions.

Upon a con­nec­tion, it will fork the appro­pri­ate process, and dis­con­nect the process when the Web­Sock­et con­nec­tion clos­es (and vice-ver­sa).

Any mes­sage sent from the Web­Sock­et client will be piped to the process’s STDIN stream, fol­lowed by a \n new­line.

Any text print­ed by the process to STDOUT shall be sent as a Web­Sock­et mes­sage when­ev­er a \n new­line is encoun­tered.

in our case this means every time a new con­nec­tion is estab­lish web­sock­etd will start a new instance of our con­sole app which in prac­tice is unlike­ly to be what we actu­al­ly want in a web­sock­et appli­ca­tion such as a mul­ti­play­er game, and in any pro­duc­tion sys­tem fork­ing will become real­ly expen­sive real­ly quick­ly!

Keep in mind though that it’s still a work-in-progress so the imple­men­ta­tion details might change in the future.