Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R socketConnection/make.socket(): any way to keep listen()ing?

Tags:

r

sockets

[Disclaimer: my knowledge of sockets is very rusty, and I'm just getting into R, so if I missed something completely obvious, please point it out!]

If I understand the (sparsely-documented) R functions for creating and managing sockets, namely socketConnection and make.socket, it appears that when creating a server socket (server=TRUE), the moral equivalent of the following is carried out:

s = socket(yada yada);
listen(s, ...);
s2 = accept(s, ...);
close(s, ...);

and now I can work with s2 but can't loop to deal with a backlog of incoming connections to s. Is this more-or-less right? Is there any way to keep listening and continue to deal with additional incoming connections after handling the first?

like image 334
Derrick Turk Avatar asked May 06 '11 14:05

Derrick Turk


1 Answers

I'd like to know the answer to this one too! ...but in the meantime I can at least suggest a work-around with some limitations:

If you can know HOW MANY clients will connect, then the following should work.

On the server:

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...
}

On each client:

port=22131
# Connect to server
s <- socketConnection('localhost', port=port)
# ...then send data...
writeLines(c('foo', 'bar'), s)
like image 79
Tommy Avatar answered Oct 08 '22 20:10

Tommy