Moon
Moon

Reputation: 22565

How to use a dynamic port # with socket.io and node.js?

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.

Upvotes: 3

Views: 1847

Answers (2)

Michelle Tilley
Michelle Tilley

Reputation: 159095

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

Upvotes: 1

Jan Jongboom
Jan Jongboom

Reputation: 27323

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.

Upvotes: 1

Related Questions