forked from mkaminsky11/codeyourcloud
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathServer.js
More file actions
81 lines (66 loc) · 2.07 KB
/
Copy pathServer.js
File metadata and controls
81 lines (66 loc) · 2.07 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Represents a websocket server
function nop() {}
// new Server() creates a new ws server and starts listening for new connections
// Events: listening(), close(), error(err), connection(conn)
// secure is a boolean that indicates if it should use tls
// options is an object to be passed to net.createServer() or tls.createServer()
// callback is a function that will be added as "connection" listener
function Server(secure, options, callback) {
var that = this
if (typeof options == "function") {
callback = options
options = undefined
}
var onConnection = function (socket) {
var conn = new Connection(socket, that, function () {
that.connections.push(conn)
conn.removeListener("error", nop)
that.emit("connection", conn)
})
conn.on("close", function () {
var pos = that.connections.indexOf(conn)
if (pos != -1)
that.connections.splice(pos, 1)
})
// Ignore errors before the connection is established
conn.on("error", nop)
}
if (secure)
this.socket = tls.createServer(options, onConnection)
else
this.socket = net.createServer(options, onConnection)
this.socket.on("close", function () {
that.emit("close")
})
this.socket.on("error", function (err) {
that.emit("error", err)
})
this.connections = []
// super constructor
events.EventEmitter.call(this)
if (callback)
this.on("connection", callback)
}
module.exports = Server
var util = require("util")
var net = require("net")
var tls = require("tls")
var Connection = require("./Connection.js")
var events = require("events")
// Makes Server also an EventEmitter
util.inherits(Server, events.EventEmitter)
// Starts listening for connections
// callback is a function that will be added as "connection" listener
Server.prototype.listen = function (port, host, callback) {
var that = this
if (typeof host == "function") {
callback = host
host = undefined
}
if (callback)
this.on("listening", callback)
this.socket.listen(port, host, function () {
that.emit("listening")
})
return this
}