如何在SocketIO中调用确认函数?

时间:2017-12-26 20:42:44

标签: javascript node.js socket.io

根据SocketIO website上的文档,我有以下代码:

服务器

socket.on('foo', (arg, ack) => {
    //Do stuff with arg
    if(ack)
        ack('response');
});

客户端

socket.emit('foo', arg, (response) => {
    console.log(response);
});

但是,永远不会调用ack函数。事实上,它是undefined。我在服务器端和客户端使用SocketIO v2.0.4。

我错过了什么吗?文档使它看起来应该很容易,但我无法理解它!

谢谢!

6 个答案:

答案 0 :(得分:2)

服务器

socket.on('foo', (arg) => {
//Do stuff with arg
    console.log('message from client : ' + data)
    socket.emit('bar','message acknowledge from server');
});

客户端

socket.emit('foo', 'mymessage');
socket.on('bar', (data) => {
    console.log(data)
});

在服务器端使用socket.io,在客户端使用socket.io-client

服务器端

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);
    });
});

客户端

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");
    }
});

答案 1 :(得分:2)

服务器端

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');
  });
});

客户端

const ioClient = require('socket.io-client');
var client = ioClient.connect('http://localhost:8090');
client.emit('ferret', 'tobu', (response) => {
  console.log(response)
  console.log('ack')
});

它将记录ack()和'ack'字符串的响应。我得到了参考socket.io acknowledge node.js sample。希望它有所帮助。

答案 2 :(得分:1)

socket.io版本与socket.io.js版本不匹配时,通常会发生此问题。这是我能够重现ack未定义的一种情况。

其他我刚用Socket 2.04测试过,它工作正常。

<强> index.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
var host = process.env.HOST || "0.0.0.0";

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

app.get('*', function (req, res) {
  console.log(' request received ', req.headers.host);
  res.status(200).send();
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });

socket.on('ferret', function (name, fn) {
    console.log('name', name, 'fn', fn);
    fn('tarun');
  });
});

http.listen(port,host, function(){
  console.log('listening on *:' + port);
  console.log('Env name is ' + process.env.name)
});

<强>的index.html

<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
      #messages { margin-bottom: 40px }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      $(function () {
        var socket = io();
socket.on('connect', function () { // TIP: you can avoid listening on `connect` and listen on events directly too!
    socket.emit('ferret', 'tobi', function (data) {
      console.log(data); // data will be 'woot'
    });
  });
        $('form').submit(function(){
          socket.emit('chat message', $('#m').val());
          $('#m').val('');
          return false;
        });
        socket.on('chat message', function(msg){
          $('#messages').append($('<li>').text(msg));
          window.scrollTo(0, document.body.scrollHeight);
        });

      });
    </script>
  </body>
</html>

<强>的package.json

{
  "name": "socket-chat-example",
  "version": "0.0.1",
  "description": "my first socket.io app",
  "dependencies": {
    "express": "^4.15.2",
    "socket.io": "^2.0.4"
  },
  "scripts": {
    "start": "node index.js"
  }
}

Working

答案 3 :(得分:0)

我暂时没有看过这个问题,但就在前几天我更新了客户端和服务器的所有SocketIO依赖关系,并且它完全符合预期。

不确定具体问题是什么,但现在似乎正在记录中。

感谢大家的投入!

答案 4 :(得分:0)

这非常简单,将来自客户端的任何.emit的最后一个参数保留为callback函数。并从服务器监听器调用此回调fn

官方文档是here

Server.js

var io = require('socket.io')(80);

io.on('connection', function (socket) {
  socket.on('ferret', function (name, fn) {
    fn('woot');
  });
});

Client.js

<script>
  var socket = io(); // TIP: io() with no args does auto-discovery
  socket.on('connect', function () { // TIP: you can avoid listening on `connect` and listen on events directly too!
    socket.emit('ferret', 'tobi', function (data) {
      console.log(data); // data will be 'woot'
    });
  });
</script>

答案 5 :(得分:0)

我也遇到了这个问题,我发现了这个问题。承认有点尴尬,但是我传递给 socket.emit() 和 socket.on() 的参数数量不匹配:

// server
socket.on('myEvent', (payload, callback) => { ... })

// client
socket.emit('myEvent', callback)

请注意,我没有向发出调用提供“有效负载”...这导致服务器上未定义“回调”。