You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.0 KiB

7 years ago
  1. # socket.io-parser
  2. [![Build Status](https://secure.travis-ci.org/socketio/socket.io-parser.svg?branch=master)](http://travis-ci.org/socketio/socket.io-parser)
  3. [![NPM version](https://badge.fury.io/js/socket.io-parser.svg)](http://badge.fury.io/js/socket.io-parser)
  4. A socket.io encoder and decoder written in JavaScript complying with version `3`
  5. of [socket.io-protocol](https://github.com/socketio/socket.io-protocol).
  6. Used by [socket.io](https://github.com/automattic/socket.io) and
  7. [socket.io-client](https://github.com/automattic/socket.io-client).
  8. ## Parser API
  9. socket.io-parser is the reference implementation of socket.io-protocol. Read
  10. the full API here:
  11. [socket.io-protocol](https://github.com/learnboost/socket.io-protocol).
  12. ## Example Usage
  13. ### Encoding and decoding a packet
  14. ```js
  15. var parser = require('socket.io-parser');
  16. var encoder = new parser.Encoder();
  17. var packet = {
  18. type: parser.EVENT,
  19. data: 'test-packet',
  20. id: 13
  21. };
  22. encoder.encode(packet, function(encodedPackets) {
  23. var decoder = new parser.Decoder();
  24. decoder.on('decoded', function(decodedPacket) {
  25. // decodedPacket.type == parser.EVENT
  26. // decodedPacket.data == 'test-packet'
  27. // decodedPacket.id == 13
  28. });
  29. for (var i = 0; i < encodedPackets.length; i++) {
  30. decoder.add(encodedPackets[i]);
  31. }
  32. });
  33. ```
  34. ### Encoding and decoding a packet with binary data
  35. ```js
  36. var parser = require('socket.io-parser');
  37. var encoder = new parser.Encoder();
  38. var packet = {
  39. type: parser.BINARY_EVENT,
  40. data: {i: new Buffer(1234), j: new Blob([new ArrayBuffer(2)])}
  41. id: 15
  42. };
  43. encoder.encode(packet, function(encodedPackets) {
  44. var decoder = new parser.Decoder();
  45. decoder.on('decoded', function(decodedPacket) {
  46. // decodedPacket.type == parser.BINARY_EVENTEVENT
  47. // Buffer.isBuffer(decodedPacket.data.i) == true
  48. // Buffer.isBuffer(decodedPacket.data.j) == true
  49. // decodedPacket.id == 15
  50. });
  51. for (var i = 0; i < encodedPackets.length; i++) {
  52. decoder.add(encodedPackets[i]);
  53. }
  54. });
  55. ```
  56. See the test suite for more examples of how socket.io-parser is used.
  57. ## License
  58. MIT