R会话能否同时建立文本与二进制Socket连接?跨机异常及方案
R双Socket跨机器通信失败问题排查与替代方案
我正在编写R程序,需要在两台机器间维持一个用于文本通信的Socket连接,同时建立第二个Socket传输文件,但跨机器运行时方案失效。
测试代码
test-server.R
textSocket <- socketConnection(host="192.168.56.101", port=9998, blocking=TRUE, server=TRUE, encoding="utf-8", timeout=300, open="r+") fileSize <- as.integer(readLines(textSocket, 1)) binSocket <- socketConnection(host="192.168.56.101", port=9999, blocking=TRUE, server=TRUE, timeout=15, open="rb") fileData <- readBin(binSocket, "raw", n=fileSize) close(binSocket) outFile <- file("fromClient.txt", open="wb") writeBin(fileData, outFile) close(outFile) close(textSocket)
test-client.R
textSocket <- socketConnection(host="192.168.56.101", port=9998, server=FALSE, blocking=TRUE, encoding="utf-8", timeout=86400, open="r+") fileSize <- as.integer(file.info("toServer.txt")$size) writeLines(toString(fileSize), textSocket) inFile <- file("toServer.txt", open="rb") fileData <- readBin(inFile, "raw", n=fileSize) close(inFile) binSocket <- socketConnection(host="192.168.56.101", port=9999, blocking=TRUE, server=FALSE, timeout=300, open="rb") writeBin(fileData, binSocket) close(binSocket) close(textSocket)
运行结果
- 本地同机器测试:将所有文件(含
toServer.txt)放在IP为192.168.56.101的机器上,两个独立R会话用source()运行程序,一切正常,工作目录生成符合预期的fromClient.txt,无警告或错误。 - 跨机器测试:在IP为192.168.56.102的机器上运行
test-client.R,程序执行到创建binSocket步骤后报错:
客户端错误
Error in socketConnection(host = "192.168.56.101", port = 9999, blocking = TRUE, : cannot open the connection In addition: Warning message: In socketConnection(host = "192.168.56.101", port = 9999, blocking = TRUE, : 192.168.56.101:9999 cannot be opened
服务器端错误
Error in socketConnection(host = "192.168.56.101", port = 9999, blocking = TRUE, : cannot open the connection In addition: Warning message: In socketConnection(host = "192.168.56.101", port = 9999, blocking = TRUE, : problem in listening on this socket
环境背景
- 两台均为VirtualBox“仅主机网络”设置的Ubuntu 22虚拟机,已安装R和RStudio
- 端口9998、9999无进程占用,更换端口后问题仍存在
疑问
R是否不允许单个会话创建两个同时存在的Socket?我在文档和相关线程中未找到相关说明,不过确实很少有人用基础R进行Socket开发。
更新:替代方案
无需使用双Socket即可同时传输文本和文件!若将主Socket(代码中的textSocket)以参数open="r+b"打开,即可在同一个Socket上同时使用readLines()、writeLines()、readBin()和writeBin(),只需跟踪数据大小即可。
内容的提问来源于stack exchange,提问作者Hilfigertout
相关产品推荐
相关产品推荐

