我在服务器端使用socket.io和nodejs来提供我的Web应用程序和服务器之间的双向通信。使用Web套接字时的请求/响应“语言”设计
我正在使用socket.io API发出命令并接收响应,但我不确定是否有更有条理的方法来定义将语法发送到服务器并从服务器接收结果的“语言”。
发送命令到服务器,我发射从Web应用程序的事件,如下面的(下面我使用伪代码):
socket.emit('commandRequest', {
msg_id: '...'
username: '...',
command: '...'
});
服务器评估该命令并发出像如下响应:·
socket.on('commandRequest', (data) => {
// parse and execute data.command
socket.emit('commandResponse', {
msg_id: data.msg_id,
username: data.username,
response: ...,
error: ...
});
})
最后,Web应用程序监听来自服务器的响应,并相应地更新应用内容:
socket.on('commandResponse', (data) => {
if (data.error) {
...
} else {
// interpret data.response
}
})
因此,我使用commandRequest/commandResponse事件命名范例,事件数据结构具有相应的{command: ...}
和{response: ...}
属性。
是否有更正式的方式来定义可用于更复杂的客户端/服务器交互的请求/响应“语言”?类似于REST API通过HTTP请求实现的功能,但使用Web套接字?