What's the net
module used for? →
It's for creating TCP/IP servers and clients.
What are the objects that we used when creating a server? →
So, how do we create a server? →
createServer
gets a callback function, though… what is this callback for? →
const net = require('net');
const server = net.createServer(function(sock) {
console.log('Got connection from (addr, port):', sock.remoteAddress, sock.remotePort);
});
server.listen(8080, '127.0.0.1');
On every connection: →
createServer
gets called with an instance a Socket
objectdata
events (that is, read data…)close
events (listen for a closed connection)write
data to the clienton
and sending it a callback that determines what to do on that eventThe classic hello world for network programming is an echo server. Here's our version. →
sock.on('data', function(binaryData) {
console.log('got data\n=====\n' + binaryData);
sock.write(binaryData);
// uncomment me if you want the connection to close
// immediately after we send back data
// sock.end();
});
So… if we try pointing our browser to our echo server, not much happens. Our server doesn't "speak HTTP" yet. What do we have to do if we want to turn our echo server into a web server that responds to different paths by sending back html documents? →
Aaand… we did just that! During our live coding demo, we came up with this code… →
First, some setup:
const net = require('net');
// Request object goes here...
const server = net.createServer(function(sock) {
// "routing" goes here
});
server.listen(8080, '127.0.0.1');
Then, a Request
object to parse out the path: →
class Request {
constructor(s) {
const requestParts = s.split(' ');
const path = requestParts[1];
this.path = path;
}
}
Now let's do routing and serving content all in one shot! →
On connection …
console.log('connected', sock.remoteAddress, sock.remotePort);
sock.on('data', (binaryData) => {
const reqString = '' + binaryData;
const req = new Request(reqString);
if(req.path === '/about') {
sock.write('HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\nhello
');
} else if(req.path === '/test') {
sock.write('HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\ntest
');
}
sock.end();
});