le_me
le_me

Reputation: 3419

Ruby: How do I receive and send data parallel?

I want to create an application that sends and receives data parallel, like a chat application. It gets input and also sends some output, but NOT only if it receives data. I want to use UDP as protocol. I'm using ruby 1.9.3.

here's the code that receives data:

@s = UDPSocket.new
@s.bind(localhost, 1234)

Socket.udp_server_loop_on([@s]) do |message, sender|
  #do something
end

This code should run independent from the rest of the application, it shouldn't block it.

Should I use a thread? I've never tried a network program and I'm not a professional developer, so please be patient. Perhaps my code/design is just crap, so feel free to tell me how this is done by professionals! ;)

Upvotes: 0

Views: 659

Answers (2)

tadman
tadman

Reputation: 211540

UDP lends itself this sort of non-blocking processing quite naturally since you're receiving individual, atomic messages over your socket and can reply in the same fashion.

Inside that loop, just be sure to process things quickly and send response messages. If you make long blocking calls it will hold up your loop and affect response times.

EventMachine provides a structure for writing asynchronous applications and has its own methods for handling UDP and TCP sockets.

Don't forget to look at solutions which are already implemented. For chat applications, Socket.IO is a great place to start.

Upvotes: 2

Ahmed Al Hafoudh
Ahmed Al Hafoudh

Reputation: 8429

You should take a look at Eventmachine gem which handles blocking IO very efficiently. Among others it also offers TCP and UDP server/client API.

Upvotes: 1

Related Questions