Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can generate a Local Server in Ruby

I want to generate ( i dont like create word) a local server (like localhost/8000) on my LAN by Ruby, i researched İnternet but i cant make it. My aim is showing html pages in local servers , using by Ruby. How can i make it?

require 'socket'

I'm using socket in Standart Library but it gives error when I refresh page.

require 'socket' 
server = TCPServer.new('localhost', 2345)
loop do
  socket = server.accept
  request = socket.gets
  STDERR.puts request
  response = "Hello World!\n"
  socket.print "HTTP/1.1 200 OK\r\n" +
           "Content-Type: text/plain\r\n" +
           "Content-Length: #{response.bytesize}\r\n" +
           "Connection: close\r\n"

  socket.print "\r\n"
  socket.print response
  socket.close
end
like image 972
serhatcileri Avatar asked Dec 27 '25 16:12

serhatcileri


2 Answers

You could do

ruby -run -e httpd -- . -p 8000

which will start server at port 8000 serving current directory (where server was started). Thus you could place all your HTML pages inside a folder and start server from there.

like image 104
Cristiano Mendonça Avatar answered Dec 30 '25 07:12

Cristiano Mendonça


Other people think you just want to start a web server, maybe your question is how to write a web server in ruby. This is a good introduction on ruby web servers and it contains an example shows how to build a sample http server, cite here for you:

require 'socket'
server = TCPServer.new 80

loop do
  # step 1) accept incoming connection
  socket = server.accept

  # step 2) print the request headers (separated by a blank line e.g. \r\n)
  puts line = socket.readline  until line == "\r\n"

  # step 3) send response

  html = "<html>\r\n"+
         "<h1>Hello, World!</h1>\r\n"+
         "</html>"

  socket.write "HTTP/1.1 200 OK\r\n" +
               "Content-Type: text/html; charset=utf-8\r\n" +
               "Content-Length: #{html.bytesize}\r\n"

  socket.write "\r\n"  # write a blank line to separate headers from the html doc
  socket.write html    # write out the html doc

  # step 4) close the socket, terminating the connection
  socket.close
end

Start it by running ruby this_file.rb, and test with a get method.

like image 30
Hailong Cao Avatar answered Dec 30 '25 09:12

Hailong Cao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!