简体   繁体   中英

Node.js connect to tcp socket after rendering express

I make node.js web server and tcp client and java tcp server. (just for study socket and web programming) I want to make program that user connects to webpage and input some information, then node sends data to java tcp server and gets echoed data and finally renders data to webpage.

My problem is that node renders webpage first and sends data to java tcp server. I want to make it sequentially. How can I solve it?

Here's my code

var net = require('net');
var rcvData;
var socket;

function getConnection(connName) {
    var client = net.connect({ port: 5000, host: '127.0.0.1' }, function () {
        console.log(connName + ' Connected: ');
        console.log('   local = %s:%s', this.localAddress, this.localPort);
        console.log('   remote = %s:%s', this.remoteAddress, this.remotePort);
        this.setEncoding('utf8');

        this.on('data', function (data) {
            rcvData = JSON.parse(data);
            console.log("From Server: " + rcvData.year);
            this.end();
        });

        this.on('end', function () {
            console.log(connName + ' Client disconnected');
        });
        this.on('error', function (err) {
            console.log('Socket Error: ', JSON.stringify(err));
        });
        this.on('timeout', function () {
            console.log('Socket Timed Out');
        });
        this.on('close', function () {
            console.log('Socket Closed');
        });
    });
    return client;
}

function writeData(socket, data) {
    var success = !socket.write(data);
    if (!success) {
        (function (socket, data) {
            socket.once('drain', function () {
                writeData(socket, data);
            });
        })(socket, data);
    }
}

// http server
var promise = require('promise');
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
var futures = require('futures');
var sequence = futures.sequence();

app.locals.pretty = true;

app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));

app.get('/', function (req, res) {
    res.render('index');
});

app.listen(8080, function () {
    console.log('http server> listening on port 8080...');

});

app.post('/result', function (req, res) {
    sequence
        .then(function(next) {
            socket = getConnection("Java TCP Server");
            next(null, 1);
        })
        .then(function (next) {
            var jsonData = {
                name: req.body.name,
                year: req.body.year
            };
            writeData(socket, JSON.stringify(jsonData));
            next(null, 2);
        })
        .then(function (next) {
            console.log('render function enter');
            console.log('rcvData : ' + rcvData);
            res.render('result', {
                name: rcvData.name,
                year: rcvData.year
            });
            next(null, 4);
        });
});

from node api https://nodejs.org/api/net.html#net_socket_write_data_encoding_callback and point to be noted

The optional callback parameter will be executed when the data is finally written out - this may not be immediately.

or simply i can say socket.write is a async function and you are expecting it sync.
also check reference Node.js flush socket after write Now i modify only a block of code, try it now

  ........

   .then(function (next) {
            var jsonData = {
                name: req.body.name,
                year: req.body.year
            };
           socket.once('drain', function () {
               socket.write(jsonData, (done)=>{
                console.log(done0);
                next(null, 2);
               });
            });

        })
  ..........

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM