Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

javascript - Local persistent variables in NodeJS WebSocket

I am trying to make persistent variable player for each WebSocket connection like this:

Server.on('request', function(request) {
    const WSCon = request.accept(null, request.origin);
    var player = "none";
    WSCon.on('message', function(message) {
        if (data.action == 0) HandleRoomEnter(player);
        if (data.action == 1) HandleReadyness(player);
    });
});

function HandleRoomEnter(player) {
    player = "Conan";
    console.log("setting: "+player);
}
function HandleReadyness(player) {
    console.log("getting: "+player);
}

However, my output is:

setting: Conan
getting: none

Where is the problem?

Thank you,

question from:https://stackoverflow.com/questions/65642046/local-persistent-variables-in-nodejs-websocket

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is the correct way of doing this:


Server.on('request', function(request) {
    const WSCon = request.accept(null, request.origin);
    let player = "none";
    function HandleRoomEnter(player) {
        player = "Conan";
        console.log("setting: "+player);
    }
    function HandleReadyness(player) {
        console.log("getting: "+player);
    }

    WSCon.on('message', function(message) {
        if (data.action == 0) HandleRoomEnter(player);
        if (data.action == 1) HandleReadyness(player);
    });
});

Also please use let or const instead of var.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...