-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
79 lines (68 loc) · 2.5 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
'use strict';
import * as constants from './constants.js';
import { packFrame, parseFrame } from './frame.js';
import http from 'http';
import crypto from 'crypto';
http.globalAgent.keepAlive = true;
function generateAcceptValue(acceptKey) {
return crypto
.createHash('sha1')
.update(acceptKey + constants.MAGIC_GUID, 'binary')
.digest('base64');
}
function byteString(n) {
if (n < 0 || n > 255 || n % 1 !== 0) {
throw new Error(n + " does not fit in a byte");
}
return ("000000000" + n.toString(2)).substr(-8)
}
const server = http.createServer();
// ===========#2
server.on('upgrade', (request, socket) => {
if('websocket' !== request.headers['upgrade']) {
socket.end('HTTP/1.1 400 Bad Request');
return;
}
setInterval(() => {
console.log(socket.readyState);
}, 1000);
// ===========#6
socket.on('data', buffer => {
for(let i = 0; i < buffer.length; i++) {
console.log(byteString(buffer[i]));
}
const frame = parseFrame(buffer);
console.log(frame.payload.toString());
// ===========#7
socket.write(packFrame(Buffer.from('This works!!!!')));
// if(frame) {
// // For our convenience, so we can see what the client sent
// console.log(message);
// // We'll just send a hardcoded message in this example
// socket.write(constructReply({ message: 'Hello from the server!' }));
// } else if (message === null) {
// console.log('WebSocket connection closed by the client.');
// }
});
const acceptKey = request.headers['sec-websocket-key'];
const hash = generateAcceptValue(acceptKey);
const responseHeaders = [
'HTTP/1.1 101 Switching Protocols',
'upgrade: websocket',
'connection: keep-alive, upgrade',
`sec-websocket-accept: ${hash}`
];
const protocol = request.headers['sec-websocket-protocol'];
const protocols = !protocol ? [] : protocol.split(',').map(s => s.trim());
// If protocol not specify, the server must send a failure response and close the connection
if(protocols.includes('wormhole')) {
responseHeaders.push(`sec-websocket-protocol: wormhole`);
}
// ===========#3
socket.write(responseHeaders.join('\r\n') + '\r\n\r\n');
setInterval(() => {
console.log(socket.readyState);
}, 2000);
});
const port = 3210;
server.listen(port, () => console.log(`Server running at http://localhost:${port}`));