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:
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.
Wayne conrad
source share