Ruby Simple Socket Promgraming

February 16, 2014 2:25 pm Ruby

Simple Server Socket

require 'socket'
i = 0;
server = TCPServer.new("",2000)
 
loop {
i = i+1
Thread.start(server.accept) do |client|
client.puts(Time.now.ctime)
client.puts "Closing the Connection"
client.close
puts i.to_s
end
}

Simple Client Socket

require 'socket'
s = TCPSocket.new('localhost',2000)
 
while line = s.gets
  puts line
 end
 
 s.close

HTTP Socket 1

require 'socket'
 
host = 'lab.kusumotolab.com'               # The web server
port = 80                               # Default HTTP port
path = "/"                    # The file we want
 
# This is the HTTP request we send to fetch a file
request = "GET #{path} HTTP/1.0\r\n\r\n"
 
socket = TCPSocket.open(host,port)      # Connect to server
socket.print(request)                   # Send request
response = socket.read                  # Read complete response
 
# Split response at first blank line into headers and body
headers,body = response.split("\r\n\r\n", 2)
print body                              # And display it

HTTP Socket 2

require 'socket'
 
addr = Addrinfo.tcp('lab.kusumotolab.com',80)
addr.connect do |socket|
socket.puts "GET /index.html HTTP/1.0\r\n\r\n"
while line = socket.gets;
  puts line
end
end