rxa
rxa

Reputation: 57

Socket.io integration Node

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.

Upvotes: 0

Views: 73

Answers (1)

jfriend00
jfriend00

Reputation: 707148

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.

Upvotes: 1

Related Questions