0

Using socket.io with nodejs and angular

myApp.factory('socket', function ($rootScope) {
  var socket = io.connect('http://localhost');

'io' not defined error

In express i'm writing:-

var io = require('socket.io').listen(app.listen(app.get('port')));
io.sockets.on('connection', function (socket) {
    console.log('io.socket connection');
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

The server is not showing error.

I am trying to follow this tutorial.

Edit:- when i add <script src="http://cdn.socket.io/stable/socket.io.js"></script>

it says connect is not a method of object 'io'

1 Answer 1

3

Socket.io is meant to be installed both on the server and on the client. By calling require() on the server you use the server-side library, but you still need to include the client-side library in the browser.

Put this somewhere in your HTML file (CDN provided by Cloudflare):

<script src="http://cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>

Note this is detailed in the basic example on the front page of the Socket.io website.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks. now it says 'connect' is not method defined.
Looks like you're using an old version of Socket.io (0.6). See my updated answer, it uses the latest stable version (0.9.16).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.