Question

So, I got node and downloaded the files, so I now have socket.io.js.

  1. How do I use it in my project? Just like a normal JavaScript file?
  2. What kind of address am I supposed to enter when I try to connect, I'm editing locally (localhost), but what about when I move it to my server?
Was it helpful?

Solution 2

Answer to the first question:

Did you use npm, node.js package manager? In case you didn't, I would highly recommend it. When using npm you don't need to manually copy individual files to your project.

How to install npm depends on you operating system.

After installation of npm you can run following command in you project folder to install socket.io package.

npm install socket.io

On the socket.io npm package page is brief get started code snippet that got me started with it on server:

var server = require('http').Server();
var io = require('socket.io')(server);

io.on('connection', function(socket){
  socket.on('event', function(data){});
  socket.on('disconnect', function(){});
});

server.listen(3000);

Source from socket.io package.

Now your server socket is at location:

http://localhost:3000

On client side:

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

Source from socket.io home page.

Answer to the second question:

What kind of address am I supposed to enter when I try to connect, I'm editing locally (localhost), but what about when I move it to my server?

You could on client side use for host and port following url:

// You might need to add the port of socket connection to the url. 
// :3000 in this case
var socket = io.connect(location.host); 

OTHER TIPS

I think - as long as it's not cross domain - you don't even have to pass the host name.
So calling the connect() method without any arguments should work.

see https://stackoverflow.com/a/15948558/1468708

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top