Am i using Node.JS TCP correctly?

26 views
Skip to first unread message

Shrekt

unread,
Jul 1, 2016, 9:35:33ā€ÆAM7/1/16
to nodejs

Hi so i just got in to Node.JS and am loving it but i am wondering if i am learning it the right way or using it right cause i don't want to learn it the wrong way then i'll have to re learn it so am basically making a simple server in Flash but i want to see if am doing it right handling client connections.

Making a new CurrentPlayer after it gets login packet setting the id and username once they connect.

Am i doing it right?

Thank you very much.



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.username = "";
    this.id = 0;
}
Reply all
Reply to author
Forward
0 new messages