与 TCP 套接字(服务器)通信

fnl*_*fnl 3 sockets r

我正在尝试使用 R 将文本发送到侦听 TCP 端口的服务器,然后从服务器读取响应文本。相当微不足道,即在 BASH 上为监听 12345 端口的服务器,即:

 > echo "text" | nc localhost 12345
 response
Run Code Online (Sandbox Code Playgroud)

服务器继续运行,此后可以随时再次查询。但是,如果我在 R 中使用 socketConnection 尝试同样的事情,我要么永远不会得到响应,要么它会被打印出来但不会被捕获。我已经尝试过以下方法:

  con <- socketConnection(port=12345)
  con <- socketConnection(port=12345, blocking=TRUE, timeout=2)
  writeLines("text", con) # server does not receive a thing
  flush(con) # has no effect
  readLines(con) # still, nothing happens and gets nothing back
  close(con) # server confirms receipt, but I no longer can get the result...
Run Code Online (Sandbox Code Playgroud)

服务器关闭连接后才收到数据,所以读不到任何内容

  con <- pipe("nc localhost 12345")
  writeLines("text", con)
Run Code Online (Sandbox Code Playgroud)

现在,“结果”被打印到 STDOUT,所以我无法捕获它......如果使用包含“文本”的临时文件:

  res <- readLines(pipe("nc localhost 12345 < tempfile"))
Run Code Online (Sandbox Code Playgroud)

这可行,但需要一个中间的临时文件。如何让服务器通信在 R 中工作,以便我可以从同一连接进行写入和读取?

Mar*_*gan 5

我编译并运行了这个简单的服务器,导致

Socket created
bind done
Waiting for incoming connections...
Run Code Online (Sandbox Code Playgroud)

然后在RI中创建了一个连接

con <- socketConnection("127.0.0.1", port = 8888)
Run Code Online (Sandbox Code Playgroud)

服务器响应

Connection accepted
Run Code Online (Sandbox Code Playgroud)

然后回到R...

writeLines("all the world's a stage", con)
x = readLines(con)
x
## [1] "all the world's a stage"
close(con)
Run Code Online (Sandbox Code Playgroud)

服务器响应的

Client disconnected
Run Code Online (Sandbox Code Playgroud)

然后如预期的那样退出。不确定这与您尝试过的有何不同。