在Node js中使用TCP连接发送数据

时间:2019-05-30 08:02:38

标签: c++ node.js tcp

我正在尝试使用节点js中的TCP连接发送数据,我的代码已经在运行,但是当我运行代码时,它将在TCP连接时停止。数据不发送。我正在使用下面的代码。请帮帮我!谢谢

我正在使用此节点js代码发送数据,我正在使用fs readline读取数据,读取该行后,它显示了所有数据,但在连接tcp时停止了。

   const net = require('net');
   const port = 5678;
   const host = 'localhost'
   const server = net.createServer();

 const fs = require('fs'); 
 const csv = require('fast-csv');

 const { 
  createReadStream } = require('fs');
 const {
   createInterface } = require('readline');


 const read = createInterface({
    input: fs.createReadStream('samplelog.txt'),
    output: process.stdout
  });

 server.listen(port, host, () => {
    console.log('TCP Server is running on port ' + port +'.');

});

let sockets = [];

server.on('connection', function(sock) {
    console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);
    sockets.push(sock);

    read.on('line', function(line) {   
            data = line;
            console.log(data);
    });

    sock.on('data', function(data) {
        console.log('DATA ' + host + ': ' + data);

        let interval = 0,
        i = 0;

        // Write the data back to all the connected, the client will receive it as data from the server
        sockets.forEach(function(sock, index, array) {
            sock.write(host + ':' + port + " said " + data + '\n');
        });
    });

    // Add a 'close' event handler to this instance of socket
    sock.on('close', function(data) {
        let index = sockets.findIndex(function(o) {
            return o.remoteAddress === sock.remoteAddress && o.remotePort === sock.remotePort;
        })
        if (index !== -1) sockets.splice(index, 1);
        console.log('CLOSED: ' + sock.remoteAddress + ' ' + sock.remotePort);
    });
});

我正在使用此代码来接收数据,我在这里使用C ++。

void TcpSocket::doConnect()
{
    socket = new QTcpSocket(this);
    connect(socket, SIGNAL(connected()),this, SLOT(connected()));
    connect(socket, SIGNAL(readyRead()),this, SLOT(readyRead()));

    qDebug() << "Connecting...";
    socket->connectToHost("127.0.0.1", 5678);

    if(socket->waitForConnected(5000) ) {
        qDebug() << "Error: " <<socket->errorString();
    }
 }

void TcpSocket::connected()
{
    qDebug() << "connected...";
    socket->write("connected.");
}

void TcpSocket::readyRead()
{
    QByteArray buffer = socket->readAll();
    qDebug() <<"Message: " << buffer;
}

发件人输出

Hello World
Hello World
Hello World
TCP Server is running on port 5678.
CONNECTED: 127.0.0.1:61077
 DATA localhost: connected.

接收器输出,输出中无数据接收。

 Connecting...
 connected...
 Error:  "Unknown error"
  Message:  "localhost:5678 said connected.\n"

0 个答案:

没有答案