Tuesday, March 17, 2009

UDP.rb

First step for my TFTP app is to build a simple UDP class.

UDP is a connectionless datagram protocol. You can bundle up some data, send it off to a target machine, and forget about the whole thing. It might not even make it to the destination; nobody cares. This has led the masses to assume that UDP is Unreliable. Consider, however, that UNIX uses UDP for internal messaging protocols. Also consider that, with just a small amount of effort, one can make lock-step communications with ACKing. This is how most networked games push their data around -- TCP would be unacceptable; it's a resource hog. And I always prefer to conserve my resources.


require "socket"

class UDP

def send( msg, host, port, flags=0 )
sock = UDPSocket.new
sock.send( msg, flags, host, port )
sock.close
end

def recv( port, maxblocksize )
sock = UDPSocket.new
sock.bind( "localhost", port )
msg = sock.recv( maxblocksize )
p sock.addr
sock.close
return msg
end
end


Two methods: send() and recv(). How much simpler can you get? I think the lack of a "connection" is a strength of UDP: the thing is just bare bones. I love that.

Here's some quick-and-dirty test code:


client = UDP.new
client.send( msg, server_addr, server_port )

server = UDP.new

loop do
msg = server.recv( server_port, maxbytes )
p msg
exit if msg.chomp.eql?( 'exit' )
sleep 1
end

2 comments: