Mike
Mike

Reputation: 783

Using socket.io from a module

My sio = require('socket.io').listen(app) is in my server.js file, but I'm calling a method in a library that would like to push a message to the client... say api.user.pushToClient()

How am I able to access sio.sockets from there? Perhaps my structure is incorrect?

Folder structure:

server.js

api

|--user.js

|--another.js

Upvotes: 7

Views: 4176

Answers (2)

user5341372
user5341372

Reputation: 1043

What I understood from the question is you want to know how to use socketIO with node module.Based on my understanding you can use it as below: First install socketIO module locally with npm by running " $npm install socket.io " command for windows.

Add Script to your HTML page:

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

Now add var io = require('socket.io'); to your server or js file where you are going to use it.

Then you can have server startup code listen to that server and on connection of it perform the options for any event.

var listener = io.listen(server);
listener.sockets.on('connection', function(socket) {
    socket.on('locationClick', function(data) {
        // perform the function on receving locationClick event.
    }
}

Upvotes: -1

janfabian
janfabian

Reputation: 404

in server.js append this line

module.exports.sio = sio; 

in api/user.js

sio = require('../server').sio;
sio.sockets.on ...

Or did I misunderstand the question?

Upvotes: 14

Related Questions