DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Simple Ruby Web Service

01.31.2011
| 3960 views |
  • submit to reddit
        Simple ruby web service with socket

Server
require 'socket'                				# Get sockets from stdlib
server = TCPServer.open(2000)   				# Socket to listen on port 2000
loop {                          				# Servers run forever
  Thread.start(server.accept) do |client|
    client.puts(Time.now.ctime) 				# Send the time to the client
	client.puts "Closing the connection. Bye!"
    client.close                				# Disconnect from the client
  end
}

client
require 'socket'      					# Sockets are in standard library

hostname = 'localhost'
port = 2000
s = TCPSocket.open(hostname, port)

while line = s.gets   					# Read lines from the socket
  puts line.chop      					# And print with platform line terminator
end
s.close               					# Close the socket when done