我在 R 中使用 svSocket 包来创建一个套接字服务器。我已经使用startSocketServer(...)成功创建了服务器。我能够将我的应用程序连接到服务器并将数据从服务器发送到应用程序。但我正在努力阅读应用程序发送的消息。我在互联网上找不到任何例子。我在 vsSocket 的文档(见下文)中仅找到了processSocket(...)示例,该示例描述了处理来自套接字的命令的函数。但我只想读取重复块中发送到服务器的套接字消息并将它们打印在屏幕上进行测试。
## Not run:
# ## A simple REPL (R eval/process loop) using basic features of processSocket()
# repl <- function ()
# {
# pars <- parSocket("repl", "", bare = FALSE) # Parameterize the loop
# cat("Enter R code, hit <CTRL-C> or <ESC> to exit\n> ") # First prompt
# repeat {
# entry <- readLines(n = 1) # Read a line of entry
# if (entry == "") entry <- "<<<esc>>>" # Exit from multiline mode
# cat(processSocket(entry, "repl", "")) # Process the entry
# }
# }
# repl()
# ## End(Not run)
谢谢你的意见。
编辑:
这里更具体的套接字服务器创建和发送消息示例:
require(svSocket)
#start server
svSocket::startSocketServer(
port = 9999,
server.name = "test_server",
procfun = processSocket,
secure = FALSE,
local = FALSE
)
#test calls
svSocket::getSocketClients(port = 9999) #ip and port of client connected
svSocket::getSocketClientsNames(port = 9999) #name of client connected
svSocket::getSocketServerName(port = 9999) #name of socket server given during creation
svSocket::getSocketServers() #server name and port
#send message to client
svSocket::sendSocketClients(
text = "send this message to the client",
sockets = svSocket::getSocketClientsNames(port = 9999),
serverport = 9999
)
...并且上面代码的响应是:
> require(svSocket)
>
> #start server
> svSocket::startSocketServer(
+ port = 9999,
+ server.name = "test_server",
+ procfun = processSocket,
+ secure = FALSE,
+ local = FALSE
+ )
[1] TRUE
>
> #test calls
> svSocket::getSocketClients(port = 9999) #ip and port of client connected
sock0000000005C576B0
"192.168.2.1:55427"
> svSocket::getSocketClientsNames(port = 9999) #name of client connected
[1] "sock0000000005C576B0"
> svSocket::getSocketServerName(port = 9999) #name of socket server given during creation
[1] "test_server"
> svSocket::getSocketServers() #server name and port
test_server
9999
>
> #send message to client
> svSocket::sendSocketClients(
+ text = "send this message to the client",
+ sockets = svSocket::getSocketClientsNames(port = 9999),
+ serverport = 9999
+ )
>
你可以看到的是:
- 成功创建套接字服务器
- 外部客户端 sock0000000005C576B0 (192.168.2.1:55427) 成功连接到服务器
- 成功向客户端发送消息(这里没有在控制台中提供 explizit 输出,但客户端响应等待
- 我仍然无法实现的是获取发送到服务器的客户端消息。有人可以给我一个例子吗?