Custom parser
Since Socket.IO v2.0.0, it is now possible to provide your own parser, in order to control the marshalling / unmarshalling of packets.
Server
const httpServer = require("http").createServer(); |
Client
const socket = io({ |
Implementing your own parser
Here is a basic example with a parser that uses the JSON.stringify()
and JSON.parse()
methods:
const Emitter = require("component-emitter"); // polyfill of Node.js EventEmitter in the browser |
The default parser
The source code of the default parser (the socket.io-parser
package) can be found here: https://github.com/socketio/socket.io-parser
Example of output:
- basic emit
socket.emit("test", 42); |
will be encoded as:
2["test",42] |
- emit with binary, acknowledgement and custom namespace
socket.emit("test", Uint8Array.from([42]), () => { |
will be encoded as:
51-/admin,13["test",{"_placeholder":true,"num":0}] |
Pros:
- the binary attachments is then base64-encoded, so this parser is compatible with browsers that do not support Arraybuffers, like IE9
Cons:
- packets with binary content are sent as two distinct WebSocket frames (if the WebSocket connection is established)
The msgpack parser
The source code of this parser can be found here: https://github.com/darrachequesne/socket.io-msgpack-parser
Sample usage:
Server
const httpServer = require("http").createServer(); |
Client (Node.js)
const socket = require("socket.io-client")("https://example.com", { |
In the browser, there is now an official bundle which includes this parser:
- https://cdn.socket.io/4.0.1/socket.io.msgpack.min.js
- cdnjs: https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.msgpack.min.js
- jsDelivr: https://cdn.jsdelivr.net/npm/socket.io-client@4.0.1/dist/socket.io.msgpack.min.js
- unpkg: https://unpkg.com/socket.io-client@4.0.1/dist/socket.io.msgpack.min.js
In that case, you don’t need to specify the parser
option.
Pros:
- packets with binary content are sent as one single WebSocket frame (if the WebSocket connection is established)
- may results in smaller payloads (especially when using a lot of numbers)
Cons:
- incompatible with browsers that do not support Arraybuffers, like IE9
- harder to debug in the Network tab of the browser