0

Hey I am new to socket and node and am playing around with making a chat using socket.io.

Here is my index.js file:

var app = require('express')();
var http = require('http').Server(app);

app.get('/', function(req, res) {
   //route handler serve index.html file
   res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket) {
    console.log('A user has connected');
    socket.on('disconnect', function() {
        console.log("A user has disconnected");
    })
})

http.listen(3000, function() {
    console.log('listening on port 3000');
});

**Here is my index.html: **

<html>
<head>
    <title> Chat </title>
    <script src="https://cdn.socket.io/socket.io-1.0.0.js"></script>
    <script>
        var socket = io();
    </script>
</head>
<body>
    <ul id="messages"></ul>
    <form action="">
        <input id="m" autocomplete="off"/> <button> Send </button>
    </form>
</body> 

I keep getting a Reference Error saying that io is not defined. I have tried linking socket as a cdn and as my server url.

2
  • 1
    Require socket.io on server as well. Try installing socket-io and add following code var io = require('socket.io')(app);. Commented Sep 22, 2016 at 1:44
  • @HimaniAgrawal thanks, this worked! Commented Sep 22, 2016 at 2:40

1 Answer 1

1

You need to load and initialize socket.io on the server side:

var app = require('express')();
var http = require('http').Server(app);

// add this line
var io = require('socket.io')(http);

This loads the socket.io module, register's it with your web server so it can hook into it and then declares and assigns the io variable.

P.S. Your client is linking to socket.io 1.0.0 which is a pretty old version at this point. You should probably let your socket.io server handle serving the socket.io client by changing your client script tag to this:

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

This will automatically serve the client the matching version of socket.io that is on your server (so they will always be in sync with the same version). This works because one of the things that require('socket.io')(app) does is it registers a route handler for /socket.io/socket.io.js.

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

2 Comments

var io = require('socket.io')(http); did the trick for me, thank you! So basically I need to reference it on both the client and server side?
@rxa - Well, you have to initialize socket.io on both client and server side.

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.