Does Rails support a neat way to listen on a UDP socket?

In Rails, it would be the best way to integrate the UDP listening process, which updated some elements of the model (in particular, he was going to add rows to one of the tables).

The simple answer seems to be to start a stream with a UDP socket object within the same process, but its not clear where I should do what works along the rails path. Is there a neat way to start listening to UDP? In particular, I would like to write a UDPController and set a specific method for each Datagram message. Ideally, I would like to avoid using HTTP over UDP (since this would lose some of what is a very valuable space in this case), but I have full control over the message format, so I can provide Rails with any information you need.

+6
ruby ruby-on-rails udp sockets
source share
2 answers

Rails is a web application framework, not a daemon server structure. If you do not know the web server that transmits UDP packets, I suppose you have to write and run a separate process and either talk to your Rails application via HTTP, or simply manipulate the database directly.

+1
source share

Let me take a step for TCP. UDP is a packet to the wind protocol that does not provide reliability. It finds use, for example, for voice over IP, where an odd dropped packet is acceptable. Using a TCP socket, you can still avoid using HTTP, and the TCP stack will handle retries, etc. For you.

The TCP server launched by inetd is the easiest in the world: you write a program that reads from stdin and writes to stdout, and then tell inetd to start this program whenever requests arrive at a specific port. You will not need to write a network code.

Here is a simple inetd tcp server:

#!/usr/bin/ruby1.8 input = gets puts "You said: #{input}" 

Here's how to tell inetd to run it:

 1024 stream tcp nowait wconrad /tmp/tcpserver.rb 

This means that you must listen to tcp connections on port 1024. When they occur, run /tmp/tcpserver.rb as the wconrad user. man inetd.conf for more information.

You can test it with telnet:

 $ telnet localhost 1024 Trying 127.0.0.1... Connected to ceres. Escape character is '^]'. Howdy! You said: Howdy! Connection closed by foreign host. $ 

Or you can use a simple client:

 $ cat /tmp/tcpclient.rb #!/usr/bin/ruby1.8 require 'socket' t = TCPSocket.new('localhost', 1024) t.puts "Hello" t.close_write puts t.read t.close $ /tmp/tcpclient.rb You said: Hello 

and just show that tcp servers in Ruby are simple:

 !/usr/bin/ruby1.8 require 'socket' def handle_session(socket) s = socket.gets socket.puts "You said: #{s}" socket.close end server = TCPServer.new('localhost', 1024) while (session = server.accept) Thread.new do handle_session(session) end end 

Because TCP is so simple, you need a good reason to worry about UDP.

+1
source share

All Articles