The net
module in Node.js allows us to create network connections. The connections that are created will be streams that we can write to and read from. This section will focus on just network connections and not HTTP. Node.js has a full HTTP module, and we will cover that in the next section.
All the functions assume that the net
module has been loaded like this:
var net = require('net');
This function will create a TCP server:
net.createServer([options], [listener])
This function allows us to listen for connections. The returned object will be a net.Server
object, and the connection listener will be passed to a net.Socket
object. We will cover both of these objects shortly.
Here is a simple example that shows us how to listen and write to a socket. Each connection will have to be manually closed:
var net = require('net'); var server = net.createServer(function (connection) { connection.write('You connected...