我正在尝试使用R向监听TCP端口的服务器发送文本,然后从服务器读取响应文本。这很简单,例如,在Bash中,对于监听12345端口的服务器:
> echo "text" | nc localhost 12345
response
服务器会一直运行,并且在此之后可以随时查询。但是如果我使用socketConnection在R中尝试相同的操作,要么永远没有响应,要么打印出来但无法捕获。 我已经尝试过以下方法:
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...
服务器只有在关闭连接后才能接收数据,因此无法读取任何内容。
con <- pipe("nc localhost 12345")
writeLines("text", con)
现在,“result”被打印到标准输出,所以我无法捕获它... 如果使用一个包含“text”的临时文件:
res <- readLines(pipe("nc localhost 12345 < tempfile"))
这样做可以实现功能,但需要一个中间的临时文件。 我该如何在R中使服务器通信工作,以便我可以从同一个连接写入并读取数据?
isIncomplete()
,可能需要在readLines之前加上writeLines("text", con2)
。 - Martin Morgan