DEV Community

Fletcher Moore
Fletcher Moore

Posted on

New to node.js and struggling with socket.io

Hi all,

Nervous first post but really need some help. I'm working on a Web application for p2p communication (both video and text).

The video communication works (some teething issues), but my main issue is getting user socket.id. specifically the user just having connected.

I have tried many things including:
Socket.on("connected", () {
console.log(socket.id);
});

All I get is "undefined". Yet if I run te same console.log code after the page loads I can get it displayed.

Not sure how to work with that.

I want to store the socket.id and username in an object/array

Thank you

Top comments (7)

Collapse
 
ats1999 profile image
Rahul kumar

Websocket is better than socket.io. There are sum bugs which causes trouble when the socket code becomes big.

Collapse
 
fletch0132 profile image
Fletcher Moore

I'll keep that in mind. It's a company project so this is just a prototype for now. Thank you

Collapse
 
ats1999 profile image
Rahul kumar

It's okey for that.

Collapse
 
peerreynders profile image
peerreynders • Edited

socket.on(eventName, listener)
Socket#id
How does that work?

Watch for the casing on the variable names:

// 1. "socket" all lowercase
const socket = io("ws://localhost:3000");

// 2. "socket" all lowercase
socket.on("connect", () => {
  // 3. "socket" all lowercase
  console.log(socket.id);
});
Enter fullscreen mode Exit fullscreen mode

Basically the listener is a function expression (arrow functions are always function expressions) - and a function has access to all the variables in the scope that created it (in this case socket).

MDN: Closures

A function declaration

const socket = io("ws://localhost:3000");

socket.on("connect", connectListener);

// function declaration...
function connectListener() {
  // ...also has access to the enclosing scope
  console.log(socket.id);
}
Enter fullscreen mode Exit fullscreen mode

would work as well.

Collapse
 
fletch0132 profile image
Fletcher Moore

Thank you. I think it was just my phone adding the caps but I'll double check my code. Thank you

Collapse
 
laub1199 profile image
Sennett Lau

I think you should pass in the "socket" param as follow:
Socket.on("connected", (socket) {
console.log(socket.id);
});

Collapse
 
fletch0132 profile image
Fletcher Moore

I'll give it a go, thank you