Ruby/Network/TCP Server
Материал из Wiki.crossplatform.ru
Содержание |
Building a Simple TCP Server
require "socket" server = TCPServer.new(1234) while connection = server.accept while line = connection.gets break if line =~ /quit/ puts line connection.puts "Received!" end connection.puts "Closing the connection. Bye!" connection.close end # To test # telnet 127.0.0.1 1234
Creating a Web Server with thread support
require "thread" require "socket" class RequestHandler def initialize(session) @session = session end def process while @session.gets.chop.length != 0 end @session.puts "HTTP/1.1 200 OK" @session.puts "content-type: text/html" @session.puts "" # End of headers @session.puts "<html>" @session.puts " <body>" @session.puts " <center>" @session.puts " <b>#{Time.now}</b>" @session.puts " <center>" @session.puts " </body>" @session.puts "</html>" @session.close end end server = TCPServer.new("0.0.0.0", "8888") $currentRequests = [] $requestedToShutDown = false while !$requestedToShutDown session = server.accept thread = Thread.new(session) do |newSession| RequestHandler.new(newSession).process end $currentRequests.push(thread) end $currentRequests.each { |t| Thread.join(t) }
Multi-Client TCP Servers
require "socket" server = TCPServer.new(1234) loop do Thread.start(server.accept) do |connection| while line = connection.gets break if line =~ /quit/ puts line connection.puts "Received!" end connection.puts "Closing the connection. Bye!" connection.close end end
To create a simple Web server, you can accept connections on the IP address 0 and the port number 80
require "socket" server = TCPServer.new("0.0.0.0", 80) loop do socket = server.accept while socket.gets.chop.length > 0 end socket.puts "HTTP/1.1 200 OK" socket.puts "Content-type: text/html" socket.puts "" socket.puts "<html>" socket.puts "<body>" socket.puts "<center>" socket.puts "<h1>#{Time.now}</h1>" socket.puts "</center>" socket.puts "</body>" socket.puts "</html>" socket.close end