我正在尝试使某些 websocket 发出的消息以双向通信的方式接收,因此如果消息从客户端丢失,客户端会重试,并且与服务器相同。我对回调不是很熟悉,我所读到的只是它们存在并且你可以使用它们,但我没有找到任何关于如何使用它们的好例子,或者我不理解这些例子。
这基本上是我现在的代码。
在 index.html 中
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
namespace = '/socket';
// Connect to the Socket.IO server.
// The connection URL has the following format:
// http[s]://<domain>:<port>[/<namespace>]
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port + namespace);
// Event handler for new connections.
// The callback function is invoked when a connection with the
// server is established.
socket.on('connect', function() {
isopen = true;
socket.emit('join_room');
});
});
});
</script>
在socks.py中
@socketio.on('join_room', namespace='/socket')
def on_room():
if 'uid' not in session:
session['uid'] = str(uuid.uuid4())
room = str(session['uid'])
print('join room {}'.format(room))
join_room(room)
因此,在此示例中,客户端 html 代码发出 join_room,我希望客户端验证服务器已收到它,如果没有再次尝试发出 join_room。
这必须双向发生。
有没有办法做到这一点?
答案 0 :(得分:0)
您可以在您的发送调用中添加回调:
socket.emit('join_room', () => { console.log('callback received!'); });
如果希望服务器在回调中传递信息,那么在服务器处理程序中添加一个return语句:
@socketio.on('join_room', namespace='/socket')
def on_room():
if 'uid' not in session:
session['uid'] = str(uuid.uuid4())
room = str(session['uid'])
print('join room {}'.format(room))
join_room(room)
return 42
然后服务器返回的任何内容都会作为参数传递给您的回调:
socket.emit('join_room', (arg) => { console.log('callback received with ' + arg); });