00001 var http = require('http')
00002 , https = require('https')
00003 , url = require('url')
00004 , EventEmitter = require('events').EventEmitter
00005 , Serializer = require('./serializer')
00006 , Deserializer = require('./deserializer')
00007
00008
00023 function Server(options, isSecure, onListening) {
00024
00025 if (false === (this instanceof Server)) {
00026 return new Server(options, isSecure)
00027 }
00028 onListening = onListening || function() {}
00029 var that = this
00030
00031
00032 if (typeof options === 'string') {
00033 options = url.parse(options)
00034 options.host = options.hostname
00035 options.path = options.pathname
00036 }
00037
00038 function handleMethodCall(request, response) {
00039 var deserializer = new Deserializer()
00040 deserializer.deserializeMethodCall(request, function(error, methodName, params) {
00041 if (Object.prototype.hasOwnProperty.call(that._events, methodName)) {
00042 that.emit(methodName, null, params, function(error, value) {
00043 var xml = null
00044 if (error !== null) {
00045 xml = Serializer.serializeFault(error)
00046 }
00047 else {
00048 xml = Serializer.serializeMethodResponse(value)
00049 }
00050 response.writeHead(200, {'Content-Type': 'text/xml'})
00051 response.end(xml)
00052 })
00053 }
00054 else {
00055 that.emit('NotFound', methodName, params)
00056 response.writeHead(404)
00057 response.end()
00058 }
00059 })
00060 }
00061
00062 this.httpServer = isSecure ? https.createServer(options, handleMethodCall)
00063 : http.createServer(handleMethodCall)
00064
00065 process.nextTick(function() {
00066 this.httpServer.listen(options.port, options.host, onListening)
00067 }.bind(this))
00068 this.close = function(callback) {
00069 this.httpServer.once('close', callback)
00070 this.httpServer.close()
00071 }.bind(this)
00072 }
00073
00074
00075 Server.prototype.__proto__ = EventEmitter.prototype
00076
00077 module.exports = Server
00078