-
Notifications
You must be signed in to change notification settings - Fork 31
/
server.js
67 lines (52 loc) · 1.59 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
var ws = require('./')
var WebSocket = require('ws')
var url = require('url')
var http = require('http')
var https = require('https')
var EventEmitter = require('events').EventEmitter
module.exports = !WebSocket.Server ? null : function (opts, onConnection) {
var emitter = new EventEmitter()
var server
if (typeof opts === 'function'){
onConnection = opts
opts = null
}
opts = opts || {}
if(onConnection)
emitter.on('connection', onConnection)
function proxy (server, event) {
return server.on(event, function () {
var args = [].slice.call(arguments)
args.unshift(event)
emitter.emit.apply(emitter, args)
})
}
var server = opts.server ||
(opts.key && opts.cert ? https.createServer(opts) : http.createServer())
var wsServer = new WebSocket.Server({
server: server,
perMessageDeflate: false,
verifyClient: opts.verifyClient
})
proxy(server, 'listening')
proxy(server, 'request')
proxy(server, 'close')
wsServer.on('connection', function (socket) {
var stream = ws(socket)
stream.remoteAddress = socket.upgradeReq.socket.remoteAddress
emitter.emit('connection', stream)
})
emitter.listen = function (addr, onListening) {
if(onListening)
emitter.once('listening', onListening)
server.listen(addr.port || addr)
return emitter
}
emitter.close = function (onClose) {
server.close(onClose)
wsServer.close()
return emitter
}
emitter.address = server.address.bind(server)
return emitter
}