Error:

TCP client example

require 'socket'

hostname = 'localhost'
port = 3000

s = TCPSocket.open(hostname, port)

s.puts("hello")
response = s.gets
puts response.chop

s.close

TCP server example

require 'socket'

server = TCPServer.open(2000)
loop {
  client = server.accept
  peer = client.peeraddr(:numeric)
  puts "Connection from #{peer[3]}:#{peer[1]}"
  client.puts(Time.now.ctime)
  client.puts "Bye!"
  client.close
}

UDP client example

require 'socket'
c = UDPSocket.new
c.send("hello\n", 0, 'localhost', 2000)
# may be less then 256 bytes
data = c.recv(256)

UDP server example

require 'socket'
s = UDPSocket.new
puts s
s.bind('localhost', 2000)
while (true) do
  text, sender = s.recvfrom(16)
  text.chomp!
  puts "Got: #{text}"
  s.send("Reply: #{text}\n", 0, sender[3], sender[1])
end

Fetch file over HTTP

require 'open-uri'
open('http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-demo.txt') do |f|
  File.open("utf8.txt","wb") do |target_f|
    target_f.write(f.read)
  end
end

Submit form using GET method

require 'net/http'
uri = URI('http://example.com/search')
params = { :limit => 10, :page => 3, :q => '%query%' }
uri.query = URI.encode_www_form(params)
puts uri

res = Net::HTTP.get_response(uri)
content = res.body if res.is_a?(Net::HTTPSuccess)

Submit form using POST method

require 'net/http'
uri = URI('http://www.quackquack42.com/search.cgi')
res = Net::HTTP.post_form(uri, 'q' => 'ruby', 'max' => '50')
puts res.body

Parse URI

require 'uri'
uri = URI('http://example.com/cgi-bin/test.cgi?q=echo')
uri.scheme   # => "http"
uri.host     # => "example.com"
uri.path     # => "/cgi-bin/test.cgi"
uri.query    # => "q=echo"

Send email via SMTP (Net::SMTP)

require 'net/smtp'

data = 'No stats'
from = 'noreply@quackquack42.com'
to = 'doe@quackquack42.com'

msg = <<END_OF_MESSAGE
From: QuackQuack42 Stats <#{from}>
To: John Doe <#{to}>
Subject: Important!

#{data}
END_OF_MESSAGE

Net::SMTP.start('192.168.1.1') do |smtp|
      smtp.send_message msg, from, to
end

Send email with attachment (mail gem)

require 'mail'

mail = Mail.new do
  from     'noreply@quackquack42.com'
  to       'doe@quackquack42.com'
  subject  'Just testing...'
  body     File.read('body.txt')
  add_file :filename => 'example.rb', :content => File.read('x.rb')
end

mail.deliver!