如果我理解你很好,给你检测服务器回调是否已被称为在客户端或没有,你可以在服务器中使用计时器并发出在客户端的确认。
让我进一步解释一下。
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秒钟后,我们显示一个叉号(☓),在两种情况下您都可以使用所需的任何功能。我们涵盖了两个方向。
希望这个帮助或至少可以为您指明正确的方向:)
非常感谢,但是我需要知道服务器中的回调函数已调用或否。示例执行以下功能或否。
// server socket.emit('message', message, function() { // this function called or no if not how do someting outside });
抱歉,您也可以从服务器发出信号,让我检查一下如何执行