0

I have the following folder structure html directory: index.html, index.html, public/js directory: main.js, socket.js, and in the root directory I have server.js

In server.js I set up the socket.io as follows :

/*********************  WEBSOKETS ***************************/

    const io = require('socket.io')(https);

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

    /************************************************ ***/

    io.on('connection', function (socket) {
        socket.on('chat message', function (msg) {
            console.log('message: ' + msg);
            io.emit('chat message', msg);
        });
    });

and in the socket.js file I handle the client part of it:

(function ($) {
    var socket = io().connect() // connect to the server

    $(function () {
        $('form').submit(function () {
            socket.emit('chat message', $('#m').val());
            $('#m').val('');
            return false;
        });
        socket.on('chat message', function (msg) {
            $('#messages').append($('<li>').text(msg));
            var happyEmoji = $('#messages').html().replace(/(\:\))/g, '&#x1F600;');
            $('#messages').html(happyEmoji);
            var sadEmoji = $('#messages').html().replace(/(\:\()/g, '&#x1F614;');
            $('#messages').html(sadEmoji);
        });
    });

})(jQuery);

but then I get the :

ReferenceError: Can't find variable: io

I also tried to place directly in my main.html file but I get the same error. I think it is because main.html is in the html directory and does not has the direct access to io in server.js this way.

How to solve it?

July333
  • 251
  • 1
  • 6
  • 15
  • Looks like a scope issue. Is that the whole server.js? If that's inside curly braces, then the scope of io is limited to that block and not visible in the socket.js file. – dwilliss May 15 '18 at 21:29

2 Answers2

1

You need to insert this line to the main.html file:

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

This sets your io variable, so you can use it:

var socket = io();

More information and examples here.

Tamas Szoke
  • 5,426
  • 4
  • 24
  • 39
0

For new people that might run into this error.

  1. After you've inserted this line below in your main.html file

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

or

<script defer src="http://localhost:3000/socket.io/socket.io.js"></script>

  1. And you've set your io variable, you also want to specified a neutral transportation method at the client side as shown below

const socket = io("http://localhost:3000", { transports: ["websocket"] });

As explained here, the default transportation method is not always allowed by all servers.

Reference this for original answer