понедельник, 11 сентября 2017 г.

Node.js Net Socket Server and Client

const net = require('net');

const HOST = '127.0.0.1'
        , PORT = 8080;

// Server

const server = net.createServer();

server.on('connection', function (serverSocket) {
    console.log('Client connected to server at ' + serverSocket.remoteAddress + ':' + serverSocket.remotePort);
    serverSocket.on('data', function (data) {
        console.log('Data from client ' + serverSocket.remoteAddress + ': ' + data);
        serverSocket.write('Client said: ' + data);
    });
    serverSocket.on('close', function () {
        console.log('Client closed connection to server: ' + serverSocket.remoteAddress +' '+ serverSocket.remotePort);
    });
    serverSocket.on('error', function (error) {
        throw error;
    })
});

server.listen(PORT, HOST, function () {
    console.log('Server started at ' + server.address().address + ':' + server.address().port);
});

// Client

const client = new net.Socket();

client.connect(PORT, HOST, function () {
    console.log('Client established connection to: ' + HOST + ':' + PORT);
    client.write('Hello');
});

client.on('data', function (data) {
    console.log('Answer from server: ' + data);
    console.log('Client ready to close connection. ');
    client.destroy(); // kill client and close connection after server's response
});

client.on('close', function () {
    console.log('Client closed his connection.');
});

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

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