Following the documentation on the SocketIO website, I have the following code:
Server
socket.on('foo', (arg, ack) => {
//Do stuff with arg
if(ack)
ack('response');
});
Client
socket.emit('foo', arg, (response) => {
console.log(response);
});
However, the ack
function is never called. As a matter of fact, it is undefined
. I am using SocketIO v2.0.4 on both server and client side.
Am I missing something? The docs make it look like it should be that easy, yet I just can't figure it out!
Thanks!
emit() doesn't have any magical powers, it just loops through all the current connected clients and calls socket. emit() for each one individually using their particular socket object - saving you the work of having to write that code yourself. From the client, socket. emit() will send a message to the server.
socket. emit - This method is responsible for sending messages. socket. on - This method is responsible for listening for incoming messages.
Description. Broadcast a message to all other connected sockets except for itself. Used most often after a socket level event occurs, eg, a new message arrived on an existing client socket.
Server side
var io = require('socket.io')(8090);
io.on('connection', function (socket) {
console.log('connected')
socket.on('ferret', function (arg, ack) {
console.log('ferret')
ack('woot');
});
});
Client side
const ioClient = require('socket.io-client');
var client = ioClient.connect('http://localhost:8090');
client.emit('ferret', 'tobu', (response) => {
console.log(response)
console.log('ack')
});
It will log the response of ack() and the 'ack' string. I got the reference socket.io acknowledge node.js sample.
Server
socket.on('foo', (arg) => {
//Do stuff with arg
console.log('message from client : ' + data)
socket.emit('bar','message acknowledge from server');
});
Client
socket.emit('foo', 'mymessage');
socket.on('bar', (data) => {
console.log(data)
});
using socket.io
in server side and socket.io-client
in client side
Server side
var app = require('http').createServer();
var io = require('socket.io')(app);
app.listen(80);
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' }, function(res) {
console.log(res);
});
});
Client side
var io = require('socket.io-client');
var socket = io('http://localhost');
socket.on('news', function (data, ack) {
console.log(data);
if(ack){
ack("acknowledge from client");
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With