user7921370
user7921370

Reputation:

Get varible to server.js from client side

Im using Socket.io to get the active users, currently I'm able to asign the username with a string but I want to transfer a variable called name to my server side aswell..

Server.js

var io =  require("socket.io")(http);
var users = [];

io.use((socket, next) => {
  users[socket.id] = {
    username: "Filip" // I want this string to be my variable name
  };
  console.log(users);
  return next();
});

Site.html

var io = io("http://localhost:3000");
var name =  <?php echo json_encode($_SESSION['displayname']); ?>;
io.emit("beautiful_name", name);

I tried to transfer the name with emit but I wasn't able to do anything that worked I'm afraid, anyone else know how I get my emit to work, or know any other solution?

This is what Im trying to acheive:

var io =  require("socket.io")(http);

var users = [];
io.on("beautiful_name", function (name){
var clientname = name;
});
io.use((socket, next) => {
  users[socket.id] = {
    username: clientname 
  };
  console.log(clientname);
  return next();
});

Upvotes: 1

Views: 71

Answers (1)

Ameer
Ameer

Reputation: 2000

You're listening to a global event on the server, I.E. listening to the IO instead of a socket. Also, you use users[socket.id] to append the user to the user array, if you want to have a key to access the user list make it an object and keep your code the same. Another issue with your code is that you are accessing the socket variable without ever initializing it, put all of your socket code in io.on("connection") to be able to communicate directly with the socket instead of with the server as a whole. Try this method, I believe it should work

var io =  require("socket.io")(http);

var users = {};
io.on("connection", function(socket) {
    socket.on("beautiful_name", function (name){
       var clientname = name;
       users[socket.id] = {
            username: clientname
       }
       console.log(clientname);
    });
  });
function getNumberOfUsers() {
   return Object.keys(users).length;
}

I hope this helps, if you need clarification please let me know.

Upvotes: 1

Related Questions