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

时间:2014-09-19 16:00:52

标签: r sockets

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

 > echo "text" | nc localhost 12345
 response

服务器继续运行,此后可以再次查询。 但是如果我在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...

服务器仅在关闭连接后才接收数据,因此无法读取任何内容

  con <- pipe("nc localhost 12345")
  writeLines("text", con)

现在,&#34;结果&#34;打印到STDOUT,所以我无法捕获它... 如果使用包含&#34; text&#34;:

的临时文件
  res <- readLines(pipe("nc localhost 12345 < tempfile"))

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

1 个答案:

答案 0 :(得分:3)

我编译并运行了这个simple server,导致

Socket created
bind done
Waiting for incoming connections...

然后在R中我创建了一个连接

con <- socketConnection("127.0.0.1", port = 8888)

服务器响应

Connection accepted

然后回到R ......

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

服务器响应

Client disconnected

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

相关问题