温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - How to be sure if a callback function has called
javascript socket.io

javascript - 如何确定是否已调用回调函数

发布于 2020-03-27 11:10:08

如何确保回调函数已调用(触发)?

我正在使用socket.io和回调函数,请查看我的代码:

// server
socket.emit('message', message, function() {
    // some code
});


// client
socket.on('message', function(data, callback) {
  callback(); // confirm we received the message
  // some code
});

我想在服务器代码中知道,以检测函数是否在客户端已调用。

查看更多

查看更多

提问者
Muhammad
被浏览
57
gengns 2019-07-04 08:12

如果我理解你很好,给你检测服务器回调是否已被称为在客户端或没有,你可以在服务器中使用计时器并发出在客户端的确认。

让我进一步解释一下。

1)服务器

// Timer to wait for your confirmation
let timer

// Listen message from the Client
socket.on('message', msg => {
  // Wait 5 s for confirmation
  timer = setTimeout(() => noConfirmation(), 5000)
  // Send message to the Clients
  io.emit('message', msg)
})

2)客户

// Listen message from the Server
socket.on('message', msg => {
  // Send confirmation (your callback)
  socket.emit('confirmation', id)
})

3)服务器

// Listen confirmation from the Client
socket.on('confirmation', id => {
  // Avoid timer
  clearTimeout(timer)
  // Send back confirmation
  io.emit('confirmation', id)
})

这里是一个完整的工作示例:

服务器(index.js)

const app = require('express')()
const http = require('http').createServer(app)
const io = require('socket.io')(http)

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

// Timer to wait for your confirmation
let timer

io.on('connection', socket => {
  console.log('a user connected')

  socket.on('disconnect', () => 
    console.log('user disconnected'))

  // Listen message from the Client
  socket.on('message', msg => {
    console.log(`message: ${msg}`)
    // Wait 5 s for confirmation
    timer = setTimeout(() => console.log('☓'), 5000)
    // Send message to the Clients
    io.emit('message', msg)
  })

  socket.on('confirmation', id => {
    console.log('✓')
    // Avoid timer
    clearTimeout(timer)
    // Send back confirmation
    io.emit('confirmation', id)
  })
})

http.listen(3000, () => 
  console.log('listening on *:3000'))

客户端(index.html)

  <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>
      const socket = io()

      // Submit message to the Server
      const $input = document.querySelector('input');
      document.querySelector('form').onsubmit = e => {
        e.preventDefault() // prevents page reloading
        socket.emit('message', $input.value)
        $input.value = ''
      }

      // Listen message from the Server
      const $messages = document.querySelector('#messages');
      socket.on('message', msg => {
        const id = new Date().getTime()
        $messages.insertAdjacentHTML('beforeend', `<li id="m${id}">${msg}</li>`)
        // Send confirmation
        socket.emit('confirmation', id)
      })

      // Confirmation message recived
      socket.on('confirmation', id => 
        document.querySelector(`#m${id}`).insertAdjacentText('beforeend', '✓'))
    </script>
  </body>

如果未收到对号(✓),则表示消息有问题,并且在服务器中5秒钟后,我们显示一个叉号(☓),在两种情况下您都可以使用所需的任何功能。我们涵盖了两个方向。

希望这个帮助或至少可以为您指明正确的方向:)