Sangram Singh
Sangram Singh

Reputation: 7191

How to include socket.io with angularjs and Express.js?

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'

Upvotes: 0

Views: 5042

Answers (1)

Paul Mougel
Paul Mougel

Reputation: 17038

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.

Upvotes: 3

Related Questions