PageRenderTime 62ms CodeModel.GetById 41ms app.highlight 4ms RepoModel.GetById 16ms app.codeStats 0ms

/js/lib/Socket.IO-node/lib/socket.io/transports/websocket/parser.js

http://github.com/onedayitwillmake/RealtimeMultiplayerNodeJs
JavaScript | 99 lines | 36 code | 20 blank | 43 comment | 6 complexity | 86ca839994a7bb956c7b8d899e44cb54 MD5 | raw file
 1
 2/*!
 3 * Socket.IO - transports - WebSocket - Parser
 4 * Copyright (c) 2010-2011 Guillermo Rauch <guillermo@learnboost.com>
 5 * MIT Licensed
 6 */
 7
 8/**
 9 * Module dependencies.
10 */
11
12var EventEmitter = require('events').EventEmitter;
13
14/**
15 * Expose `Parser`.
16 */
17
18module.exports = Parser;
19
20/**
21 * Initialize a new `Parser`.
22 *
23 * @api private
24 */
25
26function Parser(){
27  this.reset();
28};
29
30/**
31 * Inherit from `EventEmitter.prototype`.
32 */
33
34Parser.prototype.__proto__ = EventEmitter.prototype;
35
36/**
37 * Write `data`.
38 *
39 * @param {String} data
40 * @api private
41 */
42
43Parser.prototype.write = function(data){
44  this.buffer += data;
45  this.parse();
46};
47
48/**
49 * Frame the input, outputting "data" events.
50 *
51 * TODO: optimize
52 * @api private
53 */
54
55Parser.prototype.parse = function(){
56  var buf = this.buffer
57    , len = buf.length
58    , chr;
59
60  for (var i = this.pos; i < len; ++i){
61    chr = buf[i];
62
63    // verify NUL
64    if (i === 0){
65      if ('\u0000' == chr) continue;
66      this.error('Bad framing. Expected null byte as first frame');
67    }
68
69    if ('\ufffd' == chr){
70      this.emit('data', buf.substr(1, buf.length - 2));
71      this.buffer = buf.substr(i + 1);
72      this.pos = 0;
73      return this.parse();
74    }
75  }
76};
77
78/**
79 * Reset parser state.
80 *
81 * @api private
82 */
83
84Parser.prototype.reset = function(){
85  this.pos = 0;
86  this.buffer = '';
87};
88
89/**
90 * Emit an error `msg`, and reset the parser.
91 *
92 * @param {String} msg
93 * @api private
94 */
95
96Parser.prototype.error = function(msg){
97  this.reset();
98  this.emit('error', msg);
99};