[免责声明:我对套接字的了解非常生疏,我刚刚进入R,所以如果我错过了一些非常明显的东西,请指出来!]
如果我理解用于创建和管理套接字的(稀疏文档化的)R函数,即socketConnection
和make.socket
,则在创建服务器套接字(server=TRUE
)时,道德等同于以下内容:
s = socket(yada yada);
listen(s, ...);
s2 = accept(s, ...);
close(s, ...);
现在我可以使用s2
,但无法循环处理积压到s
的传入连接。这或多或少是正确的吗?有没有办法继续监听并在处理完第一个后继续处理其他传入连接?
答案 0 :(得分:2)
我也想知道这个的答案! ...但与此同时,我至少可以提出一些有限制的解决办法:
如果您知道许多客户端将连接,那么以下内容应该可以正常工作。
在服务器上:
n=2 # Number of clients
port=22131
slist=vector('list',n)
# Connect to all clients
for(i in 1:n) slist[i] <- socketConnection('localhost', port=port, server=TRUE)
# Wait for a client to send data, returns the client index
repeat {
avail <- which( socketSelect(slist) )[[1]]
# ...then read and process data, rinse, repeat...
}
在每个客户端上:
port=22131
# Connect to server
s <- socketConnection('localhost', port=port)
# ...then send data...
writeLines(c('foo', 'bar'), s)
答案 1 :(得分:-3)
不,您可以触摸s1
上的后退日志。
窗口1:
$ R
s1 = socketConnection(server=T,port=12345)
s2 = socketConnection(server=T, port=98765)
窗口2:
$ nc localhost 12345
If ever I should leave you, it wouldn't be in springtime
Knowing how in spring I'm bewitched by you so
oh no not in springtime, summer, winter, or fall
no never could I leave you at all
窗口3:
$ nc localhost 98765
for Hitler and Germany
Deutschland is happy and gay
we're marching to a faster pace
look out, here comes the Master Race!
窗口1:
readLines(s1,1)
# "if ever I should leave you, it wouldn't be in springtime"
readLines(s2,1)
# "for Hitler and Germany"
readLines(s1,1)
# "knowing how in spring I'm bewitched by you so"