如何重用TCP客户端以便在node.js

时间:2016-02-12 09:10:12

标签: javascript node.js tcp

我通过node.js使用TCP连接来连接到Windows中的某个端口,但我希望在用户注销之前建立连接。 换句话说,我想在node.js中添加TCP连接作为会话属性,这样只要用户的会话处于活动状态,它就会持续。

我试过这个,但它不起作用。

代码:

var express = require('express');
var authRouter = express.Router();
var createTCPConnection = function () {
    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 Chuck1 Norris!');
    });
    // Add a 'data' event handler for the client socket
    // data is what the server sent to this socket
    client.on('data', function(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');
    });
    return client;
};
authRouter.route('/').get(function(req, res) {
    var sess = req.session;
    if (sess.username) {
        //If Session has username attribute, it is a valid session
        res.render('dashboard', {
            title : 'Welcome To Operator Screen',
            username : sess.username
        });
        if(sess.tcpClient === undefined) {
            console.log('Establishing TcpClient');
            sess.tcpClient = createTCPConnection();
        } else {
            console.log('TcpClient already established');
        }
    } else {
        //Invalid/expired session, redirect to homepage
        res.redirect('/logout');
    } 
    });
module.exports = authRouter;

0 个答案:

没有答案