I have just started with socket.io, its giving JS Error on client page
io is not defined
How to fix this ?
http://socket.io/download/ - the official page for latest cdn.
If your server listening on port 3000 for example and your index.html connect on localhost:3000 then it will fail to include the local libraries on that port. To solve this problem, you should have already installed a normal server for example xampp and include the full url for your library to be served from xampp into your page for example : //localhost/my-project/node_modules/socket.... or just include it from cdn or use socket = io.connect('http://localhost:3000'); and load your page from normal server for example xampp
I had to do this. (For the client.)
function setup() {
var socket;
socket = io.connect('http://localhost:3000');
}
/*
This solved my error.
*/
put <script src="http://yournodeserver/socket.io/socket.io.js"></script>
into your code
I faced the same problem when using express. Even putting the server:port inside the script would not work.After the server started i would make socket listen to that port, that was mistake i guess.Changing it to below works fine
var app = express();
app.set('port', process.env.PORT || 3000);
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(app.get('port'));
On Client side I just include the script
<script src="/socket.io/socket.io.js"></script>
I have a socket app where my server (not a CDN) is serving up the socket.io.js script. So, while Emmerman is right in saying that you need to include the script tag in your client HTML code, the asset won't be loaded if your back-end is down. One option is for you to write a client-side JS script that checks for io before you try and use socket.io. If it's not present (undefined/null) then you can either conditionally show something else like, "server down" or in my case, I'm going to set a timer that keeps checking periodically until the server is restored.
[UPDATE 2] Ended up having to include the script tag, check for existence of io
object and doing a window.location.reload() after 10 seconds (using setTimeout
) (which eventually will hopefully find that the script loaded and io
exists, after which I can connect to the socket server.)
[UPDATE] I'm loading the script with an ajax call rather than using an html script tag. Then with the timer I'm checking periodically if the script will load – eventually it will when the server is restored/rebooted. jQuery ref to load JS scripts dynamically: http://api.jquery.com/jQuery.getScript/