Before we start, we should probably get a few definitions out of the way!
nc
, your browser, etc. … the connection is made from your computer to a service running on itselfNode comes with a built in net
module. It provides functions for creating servers and clients.
The following creates a server that listens on port 8080
. It will log out the address and port that connected to it.
(Details in following slide)
const net = require('net');
const HOST = '127.0.0.1';
const PORT = 8080;
const server = net.createServer((sock) => {
console.log(`got connection from ${sock.remoteAddress}:${sock.remotePort}`);
});
server.listen(PORT, HOST);
To run the above example, you'll have to have two terminal windows / tabs open.
node myFile.js
in one window
console.log
out will be shown in this windownc localhost 8080
The createServer
function:
Server
object
Again, the server object has a listen
method →
You can specify what your server will do based on specific events by using the socket object that's passed in to your anonymous function / callback for initial connection.
Some examples of socket events include:
data
- generated when socket receives dataclose
- generated when socket is closed
Use someSocketObject.on(eventName, callback)
to specify what to do on these events.
Here's an example of logging out when a socket receives data… and when a socket is closed:
// setup above
const server = net.createServer((sock) => {
sock.on('data', (binaryData) => {
console.log(`got data\n=====\n${binaryData}`);
});
sock.on('close', (data) => {
console.log(`closed - ${sock.remoteAddress}:${sock.remotePort}`);
});
});
// listen below
Let's take a closer look at one of these event handlers:
sock.on('data', function(data) {
});
The callback function for sock.on
has a single parameter, data
, which represents the binary data sent to the server.
data
is (usually) going to be a Buffer
objectBuffer
is just a representation of binary data (perhaps it's in this format because no encoding was specified!)toString
on a Buffer
object which assumes utf-8
Buffer.from("some string", encoding)
, where encoding can be:
'utf8'
'ascii'
Of course, you can also send data to the client with socket's write
and end
methods
write(data, encoding)
- sends data back to the connected client
end
- let's the client know that it wants to stop the connection
write
then end
consecutively)
Example usage demonstrating a few writes, and then an end:
sock.write('hello');
sock.write('how are you?');
sock.end('goodbye'); // lets client know connection will be closed
// (there's also sock.destroy to close the connection immediately)
Here's a server that just sends back the data that it is sent to it by the client. To have it disconnect after it gets data, uncomment sock.end()
.
// within create server
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();
});