D
D
Denis11112018-10-04 17:40:13
Node.js
Denis1111, 2018-10-04 17:40:13

Socket.io not working on Heroku?

Socket.io doesn't work on Heroku. Here is the code:

//Make Connection
const socket = io.connect('https://peaceful-shelf-32646.herokuapp.com', {
  'reconnection': true,
 	'reconnectionDelay': 1000,
   'reconnectionDelayMax' : 5000,
   'reconnectionAttempts': 5
});

//Query DOM
let message = $('#message'),
   btn = $('#send'),
   chatWin = $('#chat-window'),
   output = $('#output'),
   feedback = $('#feedback');

//functions

function send() {
  if ($.trim(message.val()) !== '') {
    socket.emit('message', {
      message: message.val()
    });
    
    message.val('');
    chatWin.stop().animate({
      scrollTop: chatWin[0].scrollHeight
    }, 800);
    return false;
  }
}

function printStatus(status, check) {
  check == null ? $('<div class="con">').append($('<b>').text(status)).appendTo(output) : check == true ? $('<div class="connect">').append($('<b>').text(status)).appendTo(output) : $('<div class="disconnect">').append($('<b>').text(status)).appendTo(output);
}

//Emit events

chatWin.scrollWithEase({
  frameRate: 60,
  animationTime: 1050,
  stepSize: 120,
  pulseAlgorithm: true,
  pulseScale: 8,
  pulseNormalize: 1,
  accelerationDelta: 20,
  accelerationMax: 1,
  keyboardSupport: true,
  arrowScroll: 50  
});

btn.on('click', () => {send()});

$(document).on('keydown',function(e) {
  if (e.keyCode == 13) send();
});

message.on('keypress', function() {
  socket.emit('typing', {});
});

//Listen for events
socket.on('message', function(username, data) {
    feedback.html('');
    output.append($('<div class="message" style="overflow-x:hidden;"></div>').append('<div class="img"><img src="/imgs/avatar.png"></div>').append($(`<div class="wrap"></div>`).append(`<strong>${username}</strong>`).append($('<div class="text"></div>').text(data.message))));
  }).on('leave', function(username) {
    printStatus(`Пользователь ${username} вышел из чата.`, null);
  }).on('connect', function() {
    printStatus("Соединение установлено", true);
    message.prop('disabled', false);
    btn.css('background-color', '#5ae4dd');
  }).on('disconnect', function() {
    printStatus("Соединение утрачено");
    message.prop('disabled', true);
    btn.css('background-color', '#999999', false);
  }).on('reconnect_faild', function() {
    alert('К сожалению, соденинение утрачено навсегда!');
  }).on('typing', function(username) {
    feedback.html(`<p><em>${username} печатает...</em></p>`);
  });

Here is the server code:
const socket = require('socket.io'),
    async = require('async'),
    cookieParser = require('cookie-parser'),
    sessionStore = require('../libs/sessionStore'),
    HttpError = require('../error').HttpError,
    User = require('../models/user').User,
    config = require('../config');

function loadSession(sid, callback) {
  sessionStore.load(sid, function (err, session) {
    if (arguments.length == 0) {
      //no arguments => no session
      return callback(null, null);
    } else {
      return callback(null, session);
    }
  });
}

function loadUser(session, callback) {
  if (!session.user) {
    return callback(null, null);
  }

  User.findById(session.user, function (err, user) {
    if (err) return callback(err);

    if (!user) {
      return callback(null, null);
    }

    callback(null, user);
  })
}

module.exports = function (server) {
  const io = socket(server);

  io.origins('localhost:*');

  const secret = config.get('session:secret');
  const sessionKey = config.get('session:name');

  io.use(function (socket, next) {
    const handshakeData = socket.request;

    async.waterfall([
      function (callback) {
        //получить sid
        let parser = cookieParser(secret);
        parser(handshakeData, {}, function (err) {
          if (err) return callback(err);

          let sid = handshakeData.signedCookies[sessionKey];

          loadSession(sid, callback);
        });
      },
      function (session, callback) {
        if (!session) {
          return callback(new HttpError(401, "No session"));
        }

        socket.handshake.session = session;
        loadUser(session, callback);
      },
      function (user, callback) {
        if (!user) {
          console.log(user);
          return callback(new HttpError(403, "Anonymous session may not connect"));
        }
        callback(null, user);
      }
    ], function (err, user) {

      if (err) {
        console.log(err);
        if (err instanceof HttpError) {
          return next(new Error('not authorized'));
        }
        next(err);
      }

      socket.handshake.user = user;
      next();

    });

  });

  io.on('connection', function (socket) {
    const userRoom = "user:room:" + socket.handshake.user.username;
    socket.join(userRoom);

    const username = socket.handshake.user.username;

    socket.broadcast.emit('join', username);

    socket.on('message', function (data) {
      io.emit('message', username, data);
    });

    socket.on('disconnect', function() {
      socket.broadcast.emit('leave', username);
    });
  });
}

Basically a connection issue. I don't know what's wrong

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question