Using socket.io from a module

2020-03-20 02:40发布

问题:

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

回答1:

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?



回答2:

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.
    }
}