Skip to content

Instantly share code, notes, and snippets.

@daffl
Last active January 6, 2022 16:43
Show Gist options
  • Save daffl/0647ac1a85458389c3b253a1388eb194 to your computer and use it in GitHub Desktop.
Save daffl/0647ac1a85458389c3b253a1388eb194 to your computer and use it in GitHub Desktop.
Socket.io counter acknowledgement example
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
let counter = 0;
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('getCounter', function(callback) {
// Increment the counter
counter++;
console.log(`Returning getCounter with counter ${counter}`);
// Use a Node style callback (error, value)
callback(null, counter);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.emit('getCounter', function(error, counter) {
console.log('Counter is', counter);
});
</script>
@anjalitomar
Copy link

hey

@dstiglr
Copy link

dstiglr commented May 7, 2020

Hey,
Can I do the same in reverse order?. I mean, send emmit from server and execute callback on client?

@riadloukili
Copy link

Hey,
Can I do the same in reverse order?. I mean, send emmit from server and execute callback on client?

Yes you can

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment