Clear net.socket of any data

77 Views Asked by At

I am writing a game server in node.js for an upcoming game that I am making. The game is written in another language (GML) and I am making the server in JavaScript. I use socket.write to send data to the client, however I don't want the previous string that I wrote in socket.write to be sent in the new message.

For exmaple: socket.write("hello!");

The client will receive the string "hello!" succesfully.

However, upon using socket.write again, this will happen:

socket.write("hello again!"):

The client will receive the string "hello!hello again!". Why is this happening and is it possible to clear the socket of any remaining information before using socket.write again?

Server code:

var net = require("net");
var port = 3000;

var server = net.createServer();

let sockets = [];
playerID = 0; 

server.on("connection",function(socket)
{
    var addr = socket.remoteAddress;
    console.log("New Connection: " + addr);
    sockets.push(socket);
    playerID += 1;
    socket.ID = playerID;
    console.log(socket.ID);
    sockets.forEach((client) => {
        client.write("Player:Connected:" + socket.ID);
        console.log("Player:Connected:" + socket.ID);
    });
    socket.on("data",function(data)
    {
        console.log("data: " + data);
        if (data.includes("Client:Disconnected")) {
            console.log(socket.remoteAddress + " has disconnected");
            const index = sockets.indexOf(socket);
            if (index > -1) { 
                sockets.splice(index, 1); //remove client from socket list 
            }      
            //Notify the other clients of the disconnect event
            sockets.forEach((socket) => {
                socket.write("Player:Disconnected:" + socket.ID);
            });     
        };
    });

    socket.once("closed",function()
    {
        console.log("Player Disconnected: " + addr);
    });
});

server.listen(port,function()
{
    console.log("The Server has been Started on port " + port);
});

I tried googling this issue but to no avail, also tried using the docs but they didn't provide any information either.

0

There are 0 best solutions below