tags:

views:

163

answers:

2

I'm creating a ruby server which is connecting to a TCP client. My server is using a TCPServer and I'm attempting to use TCPServer::recv(), but it doesn't wait for data, so just continues in a tight loop until data is received.

What is the most efficient way to process intermittant data? I'm unable to change the data being sent in since I'm attempting to emulate another server. Which read like statement from TCPServer/TCPSocket would wait for data being sent?


    require "socket"
    dts = TCPServer.new('localhost', 20000)
    s = dts.accept
    print(s, " is accepted\n")
    loopCount = 0;
    loop do
      Thread.start(s) do
        loopCount = loopCount + 1
        lineRcvd = s.recv(1024)
        if ( !lineRcvd.empty? )
          puts("#{loopCount} Received: #{lineRcvd}")
          s.write(Time.now)
        end
      end
    end
    s.close
    print(s, " is gone\n")

Thanks for your time.

A: 

Based on the questions you've been asking, I think you should try a framework like EventMachine and write a server that implements what you want instead of trying to fuss around with writing a server wrapper.

That being said, the most efficient way to read from a socket is to use a proper select call and poll all the open connections. While this is a fairly academic thing for anyone who's developed client-server applications before, it is a nuisance because there are a lot of things you can easily get wrong. For example. handling multiple connections can lead to all kinds of troublesome situations if you're not especially careful to avoid blocking calls.

The EventMachine framework makes it easy to develop query/response-type servers because you can always start with a template and work from there, for example, the built-in EventMachine::Protocols::LineAndTextProtocol one works as a great basis for most.

tadman
A: 

are you sure recv isn't returning "" -- meaning the socket is closed? If not then perhaps your sockets are set to non blocking somehow?

EventMachine is indeed far faster than using threads for socket programming :) GL. -r

rogerdpack
I'll check the options to ensure I have them set to blocking. The connection I know isn't closed since I get some responses after catching a few empty lineRcvd strings.
Dan Pieczynski
So was this actually the correct answer?
Jim