protocol.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright 2015 The MemDB Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  12. // implied. See the License for the specific language governing
  13. // permissions and limitations under the License. See the AUTHORS file
  14. // for names of contributors.
  15. 'use strict';
  16. var util = require('util');
  17. var EventEmitter = require('events').EventEmitter;
  18. var P = require('bluebird');
  19. var logger = require('memdb-logger').getLogger('memdb-client', __filename);
  20. var Protocol = function(opts){
  21. EventEmitter.call(this);
  22. opts = opts || {};
  23. this.socket = opts.socket;
  24. this.socket.setEncoding('utf8');
  25. this.remainLine = '';
  26. var self = this;
  27. this.socket.on('data', function(data){
  28. // message is json encoded and splited by '\n'
  29. var lines = data.split('\n');
  30. for(var i=0; i<lines.length - 1; i++){
  31. try{
  32. var msg = '';
  33. if(i === 0){
  34. msg = JSON.parse(self.remainLine + lines[i]);
  35. self.remainLine = '';
  36. }
  37. else{
  38. msg = JSON.parse(lines[i]);
  39. }
  40. self.emit('msg', msg);
  41. }
  42. catch(err){
  43. logger.error(err.stack);
  44. }
  45. }
  46. self.remainLine += lines[lines.length - 1];
  47. });
  48. this.socket.on('close', function(hadError){
  49. self.emit('close', hadError);
  50. });
  51. this.socket.on('connect', function(){
  52. self.emit('connect');
  53. });
  54. this.socket.on('error', function(err){
  55. self.emit('error', err);
  56. });
  57. this.socket.on('timeout', function(){
  58. self.emit('timeout');
  59. });
  60. };
  61. util.inherits(Protocol, EventEmitter);
  62. Protocol.prototype.send = function(msg){
  63. var data = JSON.stringify(msg) + '\n';
  64. var ret = this.socket.write(data);
  65. if(!ret){
  66. logger.warn('socket.write return false');
  67. }
  68. };
  69. Protocol.prototype.disconnect = function(){
  70. this.socket.end();
  71. };
  72. module.exports = Protocol;