Ruby/Network/TCPSocket

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

connect to Ruby"s Web server

require "socket"
socket = TCPSocket.new("www.ruby-lang.org", 80)
socket.puts "GET /en/index.html"
while (line = socket.gets)
    puts line
end
socket.close



Open a socket to host and port Read lines from the socket

require "socket"                # Sockets are in standard library
host, port = ARGV               # Host and port from command line
s = TCPSocket.open(host, port)  # Open a socket to host and 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



Read from a tcp server

require "socket"
host = "localhost"
port = 12345
TCPSocket.open(host, port) do |s| # Use block form of open
  while line = s.gets
    puts line.chop
  end
end                               # Socket automatically closed