вторник, 12 сентября 2017 г.

Node.js Net Socket connection full example

// --------------------------------------------------------------------------
// | Соединение между сокетами net похоже на алгоритм соединения с помощью модуля http.
// --------------------------------------------------------------------------
// | HTTP Client
// --------------------------------------------------------------------------
// | const http = require('http');
// | const server = http.createServer();
// | server.on('request', function (request, response) {
// |     request.on('data', function (data) {
// |         console.log('Request BODY from client: ' + data.toString()); // Вызывается, только, если было послано BODY
// |     });
// |     request.on('end', function () {
// |         console.log('2) Data from client ended');
// |         response.writeHead(200, 'OK', {'Content-Type': 'text/plain'});
// |         response.write('\n\r\ a. Data to client');
// |         response.end('\n\r\ b. Data to client ended');
// |         server.close();
// |     });
// | });
// | server.listen(8080, '127.0.0.1', function () {console.log('1) HTTP server started at 127.0.0.1:8080');});
// --------------------------------------------------------------------------
// | Net Server
// --------------------------------------------------------------------------
// | const net = require('net');
// | const server = net.createServer();
// | server.on('connection', function (socket) {
// |     socket.on('data', function (data) {
// |         console.log('3) Request from client: ' + data.toString());
// |     });
// |     socket.on('end', function () {
// |         console.log('5) Data from client ended');
// |     });
// |     socket.write('\n\r\ a. Data to client');
// |     socket.end('\n\r\ b. Data to client ended');
// |     server.close();
// | });
// | server.listen(8080, '127.0.0.1', function () {console.log('1) Socket server started at 127.0.0.1:8080');});
// --------------------------------------------------------------------------
// | HTTP Client
// --------------------------------------------------------------------------
// | const client = http.request({hostname: '127.0.0.1', port: 8080, path: '/', method: 'GET'});
// | client.on('response', function (response) {
// |     response.on('data', function (data) {console.log('3) Answer from server: ' + data.toString());});
// |     response.on('end', function () {console.log('4) Data from server ended');});
// | });
// | client.write('\n\r\ a. Data to server');
// | client.end('\n\r\ a. Data to server ended');
// --------------------------------------------------------------------------
// | Net Client
// --------------------------------------------------------------------------
// | const client = new net.Socket();
// | client.on('data', function (data) {console.log('2) Answer from server: ' + data.toString());});
// | client.on('end', function () {console.log('4) Data from server ended');});
// | client.on('connect', function () {
// |     client.write('\n\r\ a. Data to server');
// |     client.end('\n\r\ b. Data to server ended');
// | });
// | client.connect(8080, '127.0.0.1');
// --------------------------------------------------------------------------

const net = require('net');

// Server

const server = net.createServer(); // или тоже самое: new net.Server();

server.on('connection', function (socket) {
    socket.setEncoding('utf8');
    console.log('4) Server received connection from client: ' + socket.remoteAddress + ':' + socket.remotePort);
    socket.on('data', function (data) {
        console.log('10) Data from client: ' + data);
    });
    socket.on('end', function () {
        console.log('14) Server disconnected from client: ' + socket.remoteAddress + ':' + socket.remotePort);
        server.close();
    });
    socket.on('close', function () {
        console.log('16) Client closed connection to server.');
    });
    socket.on('error', function (error) {
        console.log('Connection client to server error: ' + error.message);
    });
    socket.write('\n\r a. Hello');
    server.getConnections(function (error, count) {
        if (error) {throw error;}
        socket.write('\n\r b. Total connections: ' + count);
        socket.end('\n\r c. Goodbye');
    });
});

server.on('close', function () {
    console.log('15) All connections to server closed.');
});

server.on('error', function (error) {
    if (error.code === 'EADDRINUSE') {
        console.log('Address in use, retrying...');
        setTimeout(function () {
            server.close();
            server.listen(9000, '127.0.0.1', function () {
                console.log('Socket server restarted at ' + JSON.stringify(server.address()));
            });
        }, 1000);
    }
});

server.on('listening', function () {
    console.log('1) Method server.listen() called.');
    if (server.listening) {
        console.log('2) Socket server is listening now.');
    }
});

server.listen(9000, '127.0.0.1', function () {
    console.log('3) Socket server started at ' + JSON.stringify(server.address()));
});

// Client

const client = new net.Socket(); // net.createConnection(); и net.connect(); вызывают "transmission error"

client.on('connect', function () {
    console.log('5) Client established connection to server.');
    console.log('6) Client socket connected at ' + JSON.stringify(client.address()));
    client.write('\n\r a. First data from client to server', 'utf8', function () {
        console.log('8) Data from client to server sent.');
    });
});

client.on('data', function (data) {
    console.log('9) Answer from server to client: ' + data);
    client.end('\n\r b. Last data from client to server.', 'utf8');
});

client.on('end', function () {
    console.log('11) Client recieved all data from server socket.');
    console.log('12) Client disconnected from server.');
});

client.on('close', function (has_error) {
    if (has_error) {
        console.log('4*) The socket was closed due to a transmission error.');
    } else {
        console.log('13) Client connection to server closed.');
    }
});

client.setTimeout(3000);
client.on('timeout', function () {
    console.log('Client connection timeout');
    client.close(); // или можно: client.destroy();
});

client.on('error', function (error) {
    console.log('3*) Client error: ' + error.message);
});

client.connect(9000, '127.0.0.1', function () {
    if (client.connecting) {
        console.log('Client socket is connecting to server socket');
    }
    console.log('7) Client connected to server.');
});

/*

// Server
1) Method server.listen() called.
2) Socket server is listening now.
3) Socket server started at {"address":"127.0.0.1","family":"IPv4", "port":9000}
4) Server received connection from client.

// Client
5) Client established connection to server.
6) Client socket connected at {"address":"127.0.0.1","family":"IPv4", "port":53977}
7) Client connected to server.
8) Data from client to server sent.
9) Answer from server to client:
 a. Hello
 b. Total connections: 1
 c. Goodbye

 // Server
10) Data from client:
 a. First data from client to server
 b. Last data from client to server.

// Client
11) Client recieved all data from server
12) Client disconnected from server.
13) Client connection to server closed.

 // Server
14) Server disconnected from client.
15) All connections to server closed.

*/

Комментариев нет:

Отправить комментарий