node.jstcpp2p

Node.js, how to keep server alive after a client exits?


I have a simple p2p app, but when I connect and exit as another peer or client the server stops completely. I've looked into connection.setKeepAlive, but it doesn't work they way I thought it would. I simply want the connection to any other peers to persist if another one exits.

const net = require('net')

const port = 3000
const host = 'localhost'

const server = net.createServer((connection) => {
    console.log('peer connected')
})

server.listen(port, () => {
    console.log('listening for peers')
})

const client = net.createConnection(port, host, () => {
    console.log('connected to peer')
})

Solution

  • In your script the port on which the server listen is the same that you use for the client connection, so the application is calling itself.

    Here is a script that connect to its peer and disconnect every 2 seconds:

    const net = require('net')
    
    const myPort = 3001
    const peerPort = 3002
    const host = 'localhost'
    
    const server = net.createServer((connection) => {
        console.log('peer connected')
    })
    
    server.listen(myPort, () => {
        console.log('listening for peers')
    })
    
    
    let connectionTest = function() {
    
        const client = net.createConnection(peerPort, host, () => {
            console.log('connected to peer')
        });
        client.on('close', (err) => {
            console.log("connection closed"); 
        });
        client.on('error', (err) => {
            console.log("error"); 
        });
    
        //TODO do stuff
    
        client.end();
        setTimeout(connectionTest, 2000);
    }
    
    setTimeout(connectionTest, 3000);
    

    For every instance you should change the ports (myPort & peerPort)