Firstly, we'll set up the client side that does not change from the official way.
If in any case you didn't follow the official guide, here is how a basic client side implementation should look like:
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io('http://localhost');
// And everything else...
</script>
As for server side, we'll have to initialize the io object passing to it 'app.server':
const Zinky = require('zinky');
var app = new Zinky();
var io = require('socket.io')(app.server);
io.on('connection', (socket) => {
console.log('socket connected')
socket.on('disconnect', () => {
console.log('socket disconnected')
});
});
Before we can use Socket.IO in app modules, we have to append it to app object and reload the modules:
So app.js will look like:
const Zinky = require('zinky');
var app = new Zinky();
var io = require('socket.io')(app.server);
app.io = io;
app.loadModules();
Tracking sockets connections is done in modules constructor.
Eg:
const Zinko = require('zinko');
class Auth extends Zinko {
constructor(dirname, app) {
super(dirname, app);
if (app.io) {
app.io.on('connection', (socket) => {
console.log('socket connected')
socket.on('disconnect', () => {
console.log('socket disconnected')
});
});
}
}
}
In operations, it is possible to use the Socket.IO server.
Eg:
const Zinko = require('zinko');
class Auth extends Zinko {
POST_login(req, res) {
// login code...
req.A.io.emit('A new logged-in user');
}
}
If we want just use Socket.IO in only one module without having to declare it in app.js, we can do that, this way:
const Zinko = require('zinko');
class Auth extends Zinko {
constructor(dirname, app) {
super(dirname, app);
this.io = require('socket.io')(app.server);
this.io.on('connection', (socket) => {
console.log('socket connected')
socket.on('disconnect', () => {
console.log('socket disconnected')
});
});
}
}
In this case, instead of using req.A.io use this.io in operations.
So, using the same example of operations we saw earlier, the code will be like this:
const Zinko = require('zinko');
class Auth extends Zinko {
POST_login(req, res) {
// login code...
this.io.emit('A new logged-in user');
}
}
Hope this helped you! If you need any help don't hesitate to ask for it here:https://github.com/zinkyJS/zinky/issues