3

When I use socket.io with node.js server, I usually use the following code (from the socket.io official site).

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost:3023');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>

as you see, I'm hard coding my server ip with port number. Is there a way to set a variable in node.js server then use the variable on my client side code?

For now, I'm using cookie.

Moon
  • 22,195
  • 68
  • 188
  • 269

2 Answers2

1

There are two basic options actually. If your socket.io client runs on the same address as your page, use:

io.connect(document.location.href);

Or, you can use a template engine to inject data from the server to the client page.

Community
  • 1
  • 1
Jan Jongboom
  • 26,598
  • 9
  • 83
  • 120
1

In recent versions of Socket.IO, you can just call io.connect() and it will auto-discover the URL.

Michelle Tilley
  • 157,729
  • 40
  • 374
  • 311