我很渴望将Socket.io集成到我的node.js项目中,但我对如何正确使用socket.io有些困惑。我一直在查阅文档和教程,但我无法理解socket.io的某些概念。
我心中所想的场景是这样的:
我心中所想的场景是这样的:
- 有多个客户端C1,C2,...,Cn
- 客户端向服务器发出请求R1,...,Rn
- 服务器接收请求并进行数据处理
- 当数据处理完成时,服务器向客户端Rs1,..,Rs2发出响应
// server listens for request from client
socket.on('request_from_client', function(data){
// user data and request_type is stored in the data variable
var user = data.user.id
var action = data.action
// server does data processing
do_some_action(..., function(rData){
// when the processing is completed, the response data is emitted as a response_event
// The problem is here, how to make sure that the response data goes to the right client
socket.emit('response_to_client', rData)
})
})
但是我没有定义我要向哪个客户端发送响应!
- socket.io如何处理这个问题?
- socket.io如何确保响应Rs1被发送到C1?
- 是什么确保了响应Rs1不会被发送到C2?
我希望我已经很好地解释了我的疑问。