Git Product home page Git Product logo

socket.io-json-parser's Introduction

socket.io-json-parser

An alternative to the default socket.io-parser, encoding and decoding packets with JSON.parse / stringify.

With that parser, binary data (ArrayBuffer / Buffer / Blob / File) is not supported.

Please note that you MUST use the parser on both sides (server & client).

See also:

Usage

const io = require('socket.io');
const ioc = require('socket.io-client');
const customParser = require('socket.io-json-parser');

const server = io(PORT, {
  parser: customParser
});

const socket = ioc('ws://localhost:' + PORT, {
  parser: customParser
});

socket.on('connect', () => {
  socket.emit('hello');
});

Format

socket.emit('hello', 'you') will create the following packet:

{
  "type": 2,
  "nsp": "/",
  "data": ["hello", "you"]
}

which will be encoded by the parser as:

{"type":2,"nsp":"/","data":["hello","you"]}

More information about the exchange protocol can be found here.

socket.io-json-parser's People

Contributors

darrachequesne avatar dependabot[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

socket.io-json-parser's Issues

Parser is swallowing errors if an error occurs in the callback for an event

Currently the Decoder method looks like this:

Decoder.prototype.add = function (obj) {
  try {
    var decoded = JSON.parse(obj);
    this.emit('decoded', decoded);
  } catch (e) {
    this.emit('decoded', errorPacket);
  }
};

If an error occurs in the emit callback (socket.io-client Manager listens for decoded, and emits packet, Socket listens for packet and calls onpacket, which eventually calls your listener) then the error is swallowed by the catch, as the errorPacket emitted instead doesn't contain the nsp property, meaning the Socket will ignore the message:

Socket.prototype.onpacket = function (packet) {
  if (packet.nsp !== this.nsp) return;
  ...

Ideally the try..catch should just encapsulate the JSON.parse call, no?

There are 2 solutions that I can see:

  1. Move the decoded declaration outside of the try..catch, then if an error is thrown, we'll be able to access the nsp property of the decoded object (with a default of '/' if the error was the JSON.parse itself):
Decoder.prototype.add = function (obj) {
  var decoded = null;
  try {
    decoded = JSON.parse(obj);
    this.emit('decoded', decoded);
  } catch (e) {
    errorPacket.nsp = (decoded) ? decoded.nsp : '/';
    this.emit('decoded', errorPacket);
  }
};

The downside to this is that the decoded event gets emitted twice for the one event

  1. Use the try..catch just for the JSON.parse, and let the client code handle any error resulting from the emit(). The downside to this is that if there is an error in JSON.parse, then we won't be able to get the nsp, so the Socket will ignore the error. That said, looking at the default socket.io parser, they seem to be returning the same object, so will have the same problem.

In that case, your method will look like:

Decoder.prototype.add = function (obj) {
  var decoded = null;
  try {
    decoded = JSON.parse(obj);
  } catch (e) {
    console.error( "Invalid JSON", e );
  }
  this.emit('decoded', (decoded) ? decoded : errorPacket);
};

It's possible that this is also what's happening in #2

Error when using socket.io v3

TypeError: callback is not a function
    at Encoder.encode (node_modules/socket.io-json-parser/index.js:27:10)
    at Client._packet (node_modules/socket.io/dist/client.js:169:44)
    at Socket.packet (node_modules/socket.io/dist/socket.js:165:21)
    at Socket._onconnect (node_modules/socket.io/dist/socket.js:209:18)
    at /Users/paiva/dev/econdos/econdos-backend/node_modules/socket.io/dist/namespace.js:130:28
    at processTicksAndRejections (internal/process/task_queues.js:79:11)

Is this parser interoperable with socket.io-parser?

Is this parser (socket.io-json-parser) interoperable with the default parser (socket.io-parser), assuming no binary data items (e.g. files, Blobs, etc.) are included in the messages? I can't find any mention of interoperability—or lack thereof—between the parsers in the documentation.

My Use Case

I have existing systems deployed with the default parser because I did not notice that alternate, more optimized parsers existed. Now that I do, I would like to update my socket.io configuration to use the optimized JSON parser. However, as new deployments will need to continue to interoperate with older systems, I need to know if the JSON parser and the default parser can interoperate (again, assuming no binary data is involved).


Related: socketio/socket.io-parser#73

Using parser results in messages not being received.

Hi, I've broken this down as much as possible and now I'm at a loss as to why nothing happens when I use this parser. Perhaps it's me doing something silly...

My server code is as follows.

const parser = require('socket.io-json-parser');
const io = require('socket.io');

let server = io(8888, {
    path: '/ws',
    parser: parser
});

server.on('connection', (socket) => {

    console.log('Socket Connection Connected');

    socket.on('disconnect', function(){
        console.log('Socket Connection Disconnected');
    });

    socket.on('checkPhone', (message) => {
        console.log(message);
    });

});

For arguments sake, this is what I'm emitting on the client side, just using the default parser:

this.socket.emit('checkPhone', JSON.stringify({phone_number: '123456'}));

If I remove the parser from the server options, then the message comes through without issue. If I use the parser in the above manner, nothing happens at all, not even an error.

Thanks in advance.

Node: 9.4.0 & 8.9.4
socket.io: 2.0.4
socket.io-json-parser: 2.1.0

EDIT:

Debug with json-parser:

  engine intercepting request for path "/ws/" +2s
  engine handling "GET" http request "/ws/?EIO=3&transport=polling&t=M603YX0" +0ms
  engine handshaking client "AyIlfNnHwZwUZ3HiAAAC" +0ms
  engine:socket sending packet "open" ({"sid":"AyIlfNnHwZwUZ3HiAAAC","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":60000}) +0ms
  engine:socket sending packet "message" ({"type":0,"nsp":"/"}) +1ms
  engine:polling setting request +0ms
  engine:socket flushing buffer to transport +0ms
  engine:polling writing "97:0{"sid":"AyIlfNnHwZwUZ3HiAAAC","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":60000}21:4{"type":0,"nsp":"/"}" +0ms
  engine:socket executing batch send callback +0ms
  socket.io:server incoming connection with id AyIlfNnHwZwUZ3HiAAAC +0ms
  socket.io:client connecting to namespace / +0ms
  socket.io:namespace adding socket to nsp / +1ms
  socket.io:socket socket connected - writing packet +0ms
  socket.io:socket joining room AyIlfNnHwZwUZ3HiAAAC +0ms
  socket.io:socket packet already sent in initial handshake +0ms
Socket Connection Connected
  socket.io:socket joined room AyIlfNnHwZwUZ3HiAAAC +0ms
  engine intercepting request for path "/ws/" +295ms
  engine handling "GET" http request "/ws/?EIO=3&transport=polling&t=M603Ybp&sid=AyIlfNnHwZwUZ3HiAAAC" +0ms
  engine setting new request for existing client +0ms
  engine:polling setting request +0ms

Debug without json-parser:

  engine intercepting request for path "/ws/" +2s
  engine handling "GET" http request "/ws/?EIO=3&transport=polling&t=M603sU5" +0ms
  engine handshaking client "qAxWH0VClDsjT4e6AAAB" +0ms
  engine:socket sending packet "open" ({"sid":"qAxWH0VClDsjT4e6AAAB","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":60000}) +0ms
  engine:socket sending packet "message" (0) +0ms
  engine:polling setting request +1ms
  engine:socket flushing buffer to transport +0ms
  engine:polling writing "97:0{"sid":"qAxWH0VClDsjT4e6AAAB","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":60000}2:40" +0ms
  engine:socket executing batch send callback +0ms
  socket.io:server incoming connection with id qAxWH0VClDsjT4e6AAAB +2ms
  socket.io:client connecting to namespace / +0ms
  socket.io:namespace adding socket to nsp / +0ms
  socket.io:socket socket connected - writing packet +1ms
  socket.io:socket joining room qAxWH0VClDsjT4e6AAAB +0ms
  socket.io:socket packet already sent in initial handshake +0ms
Socket Connection Connected
  socket.io:socket joined room qAxWH0VClDsjT4e6AAAB +0ms
  engine intercepting request for path "/ws/" +290ms
  engine handling "POST" http request "/ws/?EIO=3&transport=polling&t=M603sYf&sid=qAxWH0VClDsjT4e6AAAB" +1ms
  engine setting new request for existing client +0ms
  engine:polling received "48:42["checkPhone","{\"phone_number\":\"123456\"}"]" +0ms
  engine:socket packet +0ms
  socket.io-parser decoded 2["checkPhone","{\"phone_number\":\"123456\"}"] as {"type":2,"nsp":"/","data":["checkPhone","{\"phone_number\":\"123456\"}"]} +0ms
  socket.io:socket got packet {"type":2,"nsp":"/","data":["checkPhone","{\"phone_number\":\"123456\"}"]} +1ms
  socket.io:socket emitting event ["checkPhone","{\"phone_number\":\"123456\"}"] +0ms
  socket.io:socket dispatching an event ["checkPhone","{\"phone_number\":\"123456\"}"] +0ms
checkPhone
{"phone_number":"123456"}
  engine intercepting request for path "/ws/" +0ms
  engine handling "GET" http request "/ws/?EIO=3&transport=polling&t=M603sYg&sid=qAxWH0VClDsjT4e6AAAB" +0ms
  engine setting new request for existing client +1ms
  engine:polling setting request +0ms

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.