0

I am using Node.JS Express v4 and socket.io for implementing WebSocket.

My app.js is like this-

var express = require('express');
var socket_io = require( "socket.io" );
var path = require('path');
var favicon = require('serve-favicon');
//var controllers = require('./controllers');
//var middleware = require('./middleware');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

// Express
var app          = express();

// Socket.io
var io           = socket_io();
app.io           = io;

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.set('view options', { layout: false });     //Disabling default layout
require('./view_partials')(app);

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__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')));

require('./routes')(app);

//// Socket.io server listens to our app

    //Server - Data received
        // Send current time to all connected clients
        function sendTime()
        {
            io.emit('time', { time: new Date().toJSON() });
        }

        // Send current time every 10 secs
        setInterval(sendTime, 10000);

    //Client - Data received
        // Emit welcome message on connection
        io.on('connection', function(socket)
        {
            // Use socket to communicate with this particular client only, sending it it's own id
            socket.emit('welcome', { message: 'Welcome!', id: socket.id });
            socket.on('i am client', console.log);
        });
////////////////////////////////////////

require('./errors')(app);

module.exports = app;

I like to export this code-

    //Client - Data received
        // Emit welcome message on connection
        io.on('connection', function(socket)
        {
            // Use socket to communicate with this particular client only, sending it it's own id
            socket.emit('welcome', { message: 'Welcome!', id: socket.id });
            socket.on('i am client', console.log);
        });

to a new file.

So, what I have done is like this-

client.js-

//Client - Data received
    // Emit welcome message on connection
    io.on('connection', function(socket)
    {
        // Use socket to communicate with this particular client only, sending it it's own id
        socket.emit('welcome', { message: 'Welcome!', id: socket.id });
        socket.on('i am client', console.log);
    });

app.js-

var express = require('express');
var socket_io = require( "socket.io" );
var path = require('path');
var favicon = require('serve-favicon');
//var controllers = require('./controllers');
//var middleware = require('./middleware');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

// Express
var app          = express();

// Socket.io
var io           = socket_io();
app.io           = io;

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.set('view options', { layout: false });     //Disabling default layout
require('./view_partials')(app);

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__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')));

require('./routes')(app);

//// Socket.io server listens to our app

    //Server - Data received
        // Send current time to all connected clients
        function sendTime()
        {
            io.emit('time', { time: new Date().toJSON() });
        }

        // Send current time every 10 secs
        setInterval(sendTime, 10000);

    require('./websocket/client');
////////////////////////////////////////

require('./errors')(app);

module.exports = app;

But is is neither giving me an error or not working.

Can anyone please help, how can I export that in a separate file so that client and server code can be separated?

My full code can be found here.

Thanks in advance for helping.

Abrar Jahin
  • 13,970
  • 24
  • 112
  • 161

2 Answers2

2

I have solved the problem. We need to share the io variable to include file.

In app.js -

require('./websocket/server')(io);

And ./websocket/server.js -

// Socket.io server listens to our app
module.exports = function(io)
{
    // Send current time to all connected clients
    function sendTime()
    {
        io.emit('time', { time: new Date().toJSON() });
    }
    // Send current time every 10 secs
    setInterval(sendTime, 10000);
}

Everything is working :).

Abrar Jahin
  • 13,970
  • 24
  • 112
  • 161
-1

From http://socket.io/get-started/chat/:

Socket.IO is composed of two parts

  • A server that integrates with (or mounts on) the Node.JS HTTP Server: socket.io
  • A client library that loads on the browser side: socket.io-client

You write handlers/emitters for sockets on both the server and the client. The client-side handlers/emitters must be included in the client-side javascript for client browsers to be able to access them. Client-side javascript is always in a separate file from your server-side code.

You can check the Socket.IO getting started tutorial linked above for more information.

As a simple example, here is what you would put in your server code (your app.js). This code listens for new client connections, then emits a welcome event to the connected client.

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

// Listen for socket events
io.on('connection', function(socket) {
    // a client has connected!
    // emit a message to it
    var msg = "Hello client!"
    socket.emit('welcome', msg);
});

And here is what would go on the client (client.js):

var socket = io();

// add event listeners to the socket
// on 'welcome' event, log the response to console
socket.on('welcome', function(msg) {
    console.log(msg);
    // Hello client!
});
James Pan
  • 324
  • 1
  • 5