Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node server, Socket.io 'io is not defined'?

I've followed the exact same steps which have always previously worked for me, create application through express, place the module dependencies in the node_modules folder. It appears that the socket.io client-side javascript file isn't being found.

(I've looked at other peoples fixes, which is to include the JavaScript file in a script tab. I have not had to do this for my previous node + socket.io projects).

JavaScript on client:

var socket = io.connect('http://localhost');

JavaScript on server:

var io = require('socket.io').listen(app);

node_modules folder:

socket.io, which has an internal node_modules folder containing socket.io-client

Error Message:

Uncaught ReferenceError: io is not defined
(anonymous function)

When I include the socket.io client manually: http://cdn.socket.io/stable/socket.io.js

I get a different error which is:

Uncaught TypeError: Object #<Object> has no method 'connect'
(anonymous function)
like image 549
Jack Avatar asked Sep 29 '11 20:09

Jack


2 Answers

On the client, did you do:

<script src="/socket.io/socket.io.js"></script>

before you set the socket variable?

like image 102
Jorge Israel Peña Avatar answered Nov 21 '22 10:11

Jorge Israel Peña


Node.js newbie here! I am pretty sure this has been answered. Yet I kept finding problems with the src for the socket. Apparently this : <script src="/socket.io/socket.io.js"> was not working for me on the client side.

I've replaced the above line with this and it seems to work fine.

<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>

(Edit: although this is obvious, this link may not work depending on when you are reading this answer. Please pick the latest link from: https://cdnjs.com/libraries/socket.io)

Here is a working client side code:

<body>

<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>

<script>
    $(function(){
        var socket = io('http://localhost:8080');
        console.log("Socket connected"+socket.connected);

        socket.on('notification', function(value){
            //insert your code here
        });
    });

</script>

On the server side (handles only 1 socket)

var app  = require('express')();
var http = require('http').Server(app);
var io   = require('socket.io')(http);
var port = process.env.PORT || 8080;


app.get('/', function(req, res){
    console.log("app works");
});

io.on('connection', function(socket){
    socket.emit('notification', {message:"hi"});
});

http.listen(port, function(){
    console.log('listening on :' + port);
});
like image 21
adityah Avatar answered Nov 21 '22 10:11

adityah