Socket.io chat application not working with express?

399 views Asked by At

I need debugging help in regards to my chat application. I followed instructions from an E-Book on Socket.IO but the application will not recognize any client to server/server to client interactions. No error is reported when I run my node application so I have to idea how to debug my code. The working application should be able to send client messages to the server to be displayed by all clients with a socket connection. My "www" file in "bin" runs the node server. My folder structure is as follows:

enter image description here

www file:

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('socketio:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
require('../routes/socket.js').initialize(server);
/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

app.js:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});




module.exports = app;

public/javascripts/chat.js:

var socket = io.connect('/');
socket.on('message', function (data) {
    data = JSON.parse(data);
    $('#messages').append('<div class="'+data.type+'">' + data.message + '</div>');
});

$(function(){
    $('#send').click(function(){
        var data = {
    message: $('#message').val(),
    type:'userMessage'
        };
    socket.send(JSON.stringify(data));
    $('#message').val('');
});
});

routes/socket.js

var io = require('socket.io');

exports.initialize = function(server) {
    io = io.listen(server);
    io.sockets.on("connection", function(socket){
    socket.send(JSON.stringify(
        {type:'serverMessage',
        message: 'Welcome to the most interesting chat room on earth!'}));

    socket.on('message', function(message){
        message= JSON.parse(message);
        if(message.type == "userMessage"){
            socket.broadcast.send(JSON.stringify(message));
            message.type = "myMessage";
            socket.send(JSON.stringify(message));
        }
    });
});
};

layout.jade

doctype html
html
  block head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
    script(type='text/javascript', src='http://code.jquery.com/jquery-1.11.0.min.js')
  body
    header#banner
      h1 Awesome Chat
    block content
    footer hope you enjoy your stay here!

index.jade:

extends layout

block append head
    script(type='text/javascript', src='/socket.io/socket.io.js')
    script(type='text/javascript', src='/javascripts/chat.js')

block content
  section#chatroom
    div#messages
    input#message(type='text', placeholder='Enter your message here')
    input#send(type='button', value='Send')

0

There are 0 answers