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, '😀');
$('#messages').html(happyEmoji);
var sadEmoji = $('#messages').html().replace(/(\:\()/g, '😔');
$('#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?