-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
125 lines (100 loc) · 2.17 KB
/
index.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
const { Server } = require('./server')
const { Socket } = require('./socket')
const url = require('url')
function createServer(opts, onrequest) {
if ('function' === typeof opts) {
onrequest = opts
opts = {}
}
const server = new Server(opts)
if ('function' === typeof onrequest) {
server.on('request', onrequest)
}
return server
}
function connect(port, host, callback) {
let protocol = 'ws:'
let pathname = '/'
let opts = {}
if (port && typeof port === 'object') {
// quack
if ('object' === typeof port._ws) {
return new Socket({ socket: port._ws })
}
// quack quack
if ('function' === typeof port.send) {
return new Socket({ socket: port })
}
opts = port
callback = host
port = undefined
host = undefined
}
if (host && 'object' === typeof host) {
if (Buffer.isBuffer(host)) {
pathname = `/${host.toString('hex')}`
host = undefined
} else {
opts = host
port = undefined
host = undefined
}
}
if ('port' in opts) {
port = opts.port
}
if ('host' in opts) {
host = opts.host
}
if ('pathname' in opts) {
pathname = opts.pathname
}
if ('protocol' in opts) {
protocol = opts.protocol
}
if (typeof host === 'function') {
callback = host
host = undefined
}
if ('string' === typeof port) {
host = port
}
if (!host) {
if ('undefined' !== typeof window) {
host = window.location.hostname
if ('https:' === window.location.protocol) {
protocol = 'wss:'
}
} else {
host = 'localhost'
}
} else {
const uri = url.parse(host)
if (uri.hostname) {
host = uri.hostname
}
if (uri.port){
port = parseInt(uri.port)
}
if (uri.protocol) {
protocol = uri.protocol
}
if (uri.pathname) {
pathname = uri.pathname
}
}
if (host && port) {
const socket = new Socket(`${protocol}//${host}:${port}${pathname}`)
if ('function' === typeof callback) {
socket.on('connect', callback)
}
return socket
}
return null
}
module.exports = Object.assign(createServer, {
createServer,
connect,
Server,
Socket,
})