-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtcp-server.js
More file actions
46 lines (37 loc) · 1008 Bytes
/
Copy pathtcp-server.js
File metadata and controls
46 lines (37 loc) · 1008 Bytes
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
const net = require('net');
function responseData(str, status = 200, desc = 'OK') {
return `HTTP/1.1 ${status} ${desc}
Connection: keep-alive
Date: ${new Date()}
Content-Length: ${str.length}
Content-Type: text/html
${str}`;
}
const server = net.createServer((socket) => {
// socket.setKeepAlive(true, 600000);
socket.on('data', (data) => {
const matched = data.toString('utf-8').match(/^GET ([/\w]+) HTTP/);
if(matched) {
const path = matched[1];
if(path === '/') {
socket.write(responseData('<h1>Hello world</h1>'));
} else {
socket.write(responseData('<h1>Not Found</h1>', 404, 'NOT FOUND'));
}
}
console.log(`DATA:\n\n${data}`);
});
socket.on('close', () => {
console.log('connection closed, goodbye!\n\n\n');
});
}).on('error', (err) => {
// handle errors here
throw err;
});
server.listen({
host: '0.0.0.0',
port: 10080,
// exclusive: true,
}, () => {
console.log('opened server on', server.address());
});