How to send/route key press from client side to node child process using nodejs?

I am using node.js to spawn a child process (which happens to be a video game) on click of an HTML element. The client and the server are meant to be on the same machine of course. When I do this now, the game opens but all keyboard presses are going to the browser of course and not the full screen game that opens on spawning.

How could I route all keyboard presses from client to the child process(game)?

My only thought is to have the client listen for key presses, and pass those (via something like Socket.IO) to node which in turn would send those to the child. I'm afraid this would cause lag between key press and the game. Also, i am not even sure how to send an actual key press to a child process in the first place.

-- here is how i am spawning the process --

var spawn = require('child_process').spawn;
var prc = spawn('gameinquestion',  ['-v']);

The idea:

  • bind a keydown event on the window of your navigator
  • forward keys to Node via ajax (Bear in mind that you'll need to choose a trade-off on this one. You can either send the keys one by one, which leads to either concurrency issues or high latency - more on this later. Or you can send the keys bunched in packets, which means that you'll be delaying certain keystrokes by quite a bit)
  • Node conveys the keystrokes using a native solutions (I am not sure what platform you're on)

For what you are doing (playing a game), however, you may want to knock Node out of the equation completely and get something like http://badassjs.com/post/711624134/novnc-a-vnc-viewer-in-javascript (a VNC client in pure JS).

More on the latency

If you convey the keystrokes one by one, you will need to worry about the fact that some requests, which will fire later, will actually arrive faster (sometimes by little, sometimes by a lot). This may or may not change the order on which separate requests hit the Node server. What you will always want to do if you are conveying the keystrokes one by one is to have Node send back a unique ID of the "last keystroke received", so that the client knows which one it is on...or have the client keep a count of the number of keystrokes it received, sending the current with all the keystrokes it send, and having the server re-build the order.

The second option is a packet solution - instead of sending one keystroke, you bunch them in either x keystrokes or x milliseconds' worth of keystrokes. The first is nice if you're typing a lot, as the updates will be quicker, but worse if you type very little. The second is nice because you know that you'll be delayed at most by x. IT sucks, however, because you know that you've got to rely on fluke to be delayed by less than x.

Also, even in case #2, unless you pick a stupidly large packeting frame, you'll need to implement solution #1.