artdaq_node_server  v1_00_09
 All Classes Namespaces Files Variables Pages
server.js
1 var http = require('http')
2  , https = require('https')
3  , url = require('url')
4  , EventEmitter = require('events').EventEmitter
5  , Serializer = require('./serializer')
6  , Deserializer = require('./deserializer')
7 
8 
23 function Server(options, isSecure, onListening) {
24 
25  if (false === (this instanceof Server)) {
26  return new Server(options, isSecure)
27  }
28  onListening = onListening || function() {}
29  var that = this
30 
31  // If a string URI is passed in, converts to URI fields
32  if (typeof options === 'string') {
33  options = url.parse(options)
34  options.host = options.hostname
35  options.path = options.pathname
36  }
37 
38  function handleMethodCall(request, response) {
39  var deserializer = new Deserializer()
40  deserializer.deserializeMethodCall(request, function(error, methodName, params) {
41  if (Object.prototype.hasOwnProperty.call(that._events, methodName)) {
42  that.emit(methodName, null, params, function(error, value) {
43  var xml = null
44  if (error !== null) {
45  xml = Serializer.serializeFault(error)
46  }
47  else {
48  xml = Serializer.serializeMethodResponse(value)
49  }
50  response.writeHead(200, {'Content-Type': 'text/xml'})
51  response.end(xml)
52  })
53  }
54  else {
55  that.emit('NotFound', methodName, params)
56  response.writeHead(404)
57  response.end()
58  }
59  })
60  }
61 
62  this.httpServer = isSecure ? https.createServer(options, handleMethodCall)
63  : http.createServer(handleMethodCall)
64 
65  process.nextTick(function() {
66  this.httpServer.listen(options.port, options.host, onListening)
67  }.bind(this))
68  this.close = function(callback) {
69  this.httpServer.once('close', callback)
70  this.httpServer.close()
71  }.bind(this)
72 }
73 
74 // Inherit from EventEmitter to emit and listen
75 Server.prototype.__proto__ = EventEmitter.prototype
76 
77 module.exports = Server
78