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.
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);
});
I managed to blunder through this, and squandered about an hour, on something that turned out to be a very basic error.
When an function is not defined? Such as " Uncaught ReferenceError: io is not defined ". Does that not mean that the function is getting "used" before it is "created"?
In the part of my HTML file, that "calls" the javaScript files, it look like this :
<script src='./js/playerChatter.js'></script> <!-- this one calls io -->
<script src="http://localhost:2019/socket.io/socket.io.js"></script><!--ThisCreatesio-->
and i changed it to this
<script src="http://localhost:2019/socket.io/socket.io.js"></script> <!--ThisCreates io-->
<script src='./js/playerChatter.js'></script> <!-- this on calls io -->
So now the item "io", whether it is an object or function... Is actually getting created before it is getting used :D
Have FUN!
On the client:
<head>
<script src="http://localhost/socket.io/socket.io.js"></script>
</head>
I solved this by running the index page by the Node.js server.
Most likely "index.html" and "/socket.io/socket.io.js" files should be served by your Node.js server.
as mentioned in the url Uncaught ReferenceError: io is not defined
So when I executed https://localhost:3000
(3000 the port where the nodejs has been started) the error got resolved.
On the client, did you do:
<script src="/socket.io/socket.io.js"></script>
before you set the socket
variable?