【问题标题】:Request/response "language" design when using Web Sockets使用 Web Sockets 时的请求/响应“语言”设计
【发布时间】:2016-10-13 17:20:08
【问题描述】:

我在服务器端使用带有 nodejs 的 socket.io 在我的 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 套接字?

【问题讨论】:

    标签: node.js websocket socket.io


    【解决方案1】:

    您可以尝试查看Primus 及其Responder 插件,如本博文所述:Request-Response Oriented Websockets

    帖子摘录:

    它允许使用其他库中已知的简单 API 向对端请求响应。

    Primus Responder 为 Primus 的核心功能添加了两件事:

    1. 一旦对等方请求响应,就会发出一个名为 request 的新事件。
    2. 名为writeAndWait(data, fn) 的新方法将数据写入对等点,并在对等点发送响应时运行给定的回调函数。

    客户端也可以使用 Primus Responder。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-28
      • 1970-01-01
      • 1970-01-01
      • 2016-10-29
      • 2015-01-03
      • 1970-01-01
      相关资源
      最近更新 更多