Efficient way to create a buffer with a schema and send it over WebSockets in Javascript?
<p>I'm writing a browser game and am looking for a way to send raw array buffers to and from the <code>node.js</code> server.</p>

<p>I don't like the idea of sending <code>JSON</code> strings over <code>WebSockets</code> because:</p>

<ol>
<li>I have to specify keys when the receiver already knows the format</li>
<li>There is no validation or checking if you send malformed structure (not required though)</li>
<li>Parsing JSON strings in to objects is inherently slower than reading binary</li>
<li>Wasted bandwidth from the entire payload being a string (instead of packed ints, for example)</li>
</ol>

<p>Ideally, I would be able to have a schema for every message type, construct that message, and send its raw array buffer to the server. Something like this:</p>

<pre><code>schema PlayerAttack {
  required int32 damage;
  required int16[] coords;
  required string name;
}

var message = new PlayerAttack(5, [24, 32], "John");
websockets.send(message.arrayBuffer());
</code></pre>

<p>And it would then arrive at the Node.js server as a Buffer with the option to decode in to an object.</p>

<p>Google's <a href="https://www.npmjs.com/package/protobufjs" rel="nofollow">Protocol Buffers</a> almost fits this use-case, but are too slow and have too much overhead (7x slower than <code>JSON.parse</code> from my benchmark and includes features like tagging which I have no use for).</p>