Matt
Matt

Reputation: 1757

socket.io onconnect send extra data

I am using socket.io and currently everything is great however I want to send data to a specific client. However I am unsure how to get sed clients socket id. I want to send extra data on connection.

I have tried:

if (steamID != "" && steamName != "") {
    socket.emit("username", { 
        socketData: {
            name: steamName
        }
    });
}

and serverside:

socket.on('username', function (data) {
    socket.username = data.socketData.name;
});

clients[socket.id] = {
    id: socket.id,
    ip: socket.request.connection.remoteAddress,
    name: socket.username
    cons
}

console.log(clients);

However I just get name: undefined

Upvotes: 0

Views: 157

Answers (1)

jahnestacado
jahnestacado

Reputation: 593

In which part of your code you check the value of the name property? The code that you provide will first assign the value of undefined to clients[socket.id].name, since the socket.username is not defined yet. When the on("username") event is invoked then it will assign a value to socket.username. If you put a console.log(data) inside the message callback what do you get?

Upvotes: 1

Related Questions