2
\$\begingroup\$

I just got into Node.JS and am loving it but I am wondering if I am learning it the right way or using it. This is basically a simple server in Flash but I want to see if am doing it right with handling client connections. This makes a new CurrentPlayer after it gets a login packet and sets the ID and username once they connect.

const net = require('net');

const server = net.createServer((c) => {

    c.on('end', () => {
        console.log('client disconnected');
    });

    c.on('data', function(data) {
        console.log('DATA ' + c.remoteAddress + ': ' + data);
        CheckPacket(data.toString(), c);
    });

    c.on('close', function(data) {
        console.log('CLOSED: ' + c.remoteAddress +' '+ c.remotePort);
    });
});

server.on('connection', function (c) {
    console.log('client connected > ' + c.remoteAddress);
});

server.on('error', (err) => {
    throw err;
});
server.listen(888, () => {
    console.log('Server listening on 888');
});


function CheckPacket(packet, client) {
    if (packet.startsWith("<")) {
        client.write("<cross-domain-policy><allow-access-from domain='*' to-ports='888'/></cross-domain-policy>\0");
    } else {
        var re = /\0/g;
        packet = packet.toString().replace(re, "");
        var json = JSON.parse(packet);
        JsonPacket(json, client);
    }
}

function JsonPacket(json, client) {
    switch (json.type) {
        case 'login':

            client.name = new CurrentPlayer();
            client.name.id = json.id;

            console.log(client.name);

            break;

        default:
            console.log('Unknown json: ' + json);
            break;
    }
}


function CurrentPlayer() {
    this.id = 0;
}
\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.