Netsocket.js

Материал из support.qbpro.ru

Полная версия

Сервер

var net = require('net');
var HOST = '127.0.0.1';
var PORT = 6969;

// Создание сервера, с прослушкой (в цепочке вызова фукции)
// Фунцкия передается net.createServer() и начинает прослушивать событие 'connection' 
// The sock object the callback function receives UNIQUE for each connection
net.createServer(function(sock) {
    
    // Соединение установлено - объект socket ассоциируется с соединением автоматически
    console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
    
    // Добавляем прослушку на событие 'data' для этой реализации сокета
    sock.on('data', function(data) {
        
        console.log('DATA ' + sock.remoteAddress + ': ' + data);
        // Write the data back to the socket, the client will receive it as data from the server
        sock.write('You said "' + data + '"');
        
    });
    
    // Add a 'close' event handler to this instance of socket
    sock.on('close', function(data) {
        console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
    });
    
}).listen(PORT, HOST);

console.log('Server listening on ' + HOST +':'+ PORT);

Клиент

var net = require('net');

var HOST = '127.0.0.1';
var PORT = 6969;

var client = new net.Socket();
client.connect(PORT, HOST, function() {

    console.log('CONNECTED TO: ' + HOST + ':' + PORT);
    // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client 
    client.write('I am Chuck Norris!');

});

// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
    
    console.log('DATA: ' + data);
    // Close the client socket completely
    client.destroy();
    
});

// Add a 'close' event handler for the client socket
client.on('close', function() {
    console.log('Connection closed');
});

Адаптированная рабочая версия