【问题标题】:How to send a WebSocket message from an httpuv server in R without using message callback?如何在不使用消息回调的情况下从 R 中的 httpuv 服务器发送 WebSocket 消息?
【发布时间】:2022-11-17 10:58:18
【问题描述】:

我已经设置了一个简单的 httpuv WebSocket 服务器,它可以从 WebSocket 客户端接收消息并在收到后回显它们。

例如:

library(httpuv)

s <- startServer("0.0.0.0", 8080, 
                 list(
                   onWSOpen = function(ws) {
                     ws$onMessage(function(binary, message) {
                       ws$send(message)
                     })
                   })
)

是否可以在 ws$onMessage 回调之外向该 WebSocket 客户端发送消息?

作为我想象的语法结构的一个例子,我希望能够调用:s$ws$send("Hello")并将Hello发送到客户端,而不需要客户端消息/使用任何回调函数.

【问题讨论】:

    标签: r websocket httpuv


    【解决方案1】:

    为了回答我自己的问题,我后来发现使用 R 中的超级赋值运算符可以做到这一点:

    library(httpuv)
    
    w <- NULL
    s <- startServer("0.0.0.0", 8080, 
                     list(
                       onWSOpen = function(ws) {
                         w <<- ws  # Now, the WebSocket object persists in the global environment
    
                         ws$onMessage(function(binary, message) {
                           ws$send(message)
                         })
                       })
    )
    
    # Wait for client to connect...
    
    w$send("Hello")  # Send message to the client
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-25
      • 1970-01-01
      相关资源
      最近更新 更多