Rails Insights

Building Your Own Web Server with Ruby

Introduction

Are you interested in learning how to build your own web server using Ruby? In this article, we will guide you through the process of creating a simple web server from scratch using Ruby programming language. By the end of this tutorial, you will have a basic understanding of how web servers work and how you can create your own using Ruby.

Prerequisites

Before we get started, make sure you have Ruby installed on your computer. You can check if Ruby is installed by running the following command in your terminal:

ruby -v

If Ruby is not installed, you can download and install it from the official Ruby website.

Creating a Simple Web Server

Now that you have Ruby installed, let's start by creating a simple web server. Open your favorite text editor and create a new file called server.rb. In this file, we will write the code for our web server.

require 'socket'

server = TCPServer.new('localhost', 3000)

loop do
  client = server.accept

  client.puts "HTTP/1.1 200 OK"
  client.puts "Content-Type: text/html"
  client.puts
  client.puts "Hello, World!"

  client.close
end

In the code above, we are creating a new TCP server that listens on localhost port 3000. When a client connects to the server, we send a simple HTTP response with the message "Hello, World!".

Running the Web Server

To run the web server, save the server.rb file and open your terminal. Navigate to the directory where the file is saved and run the following command:

ruby server.rb

Once the server is running, open your web browser and navigate to http://localhost:3000. You should see the message "Hello, World!" displayed on the page.

Customizing the Web Server

Now that you have a basic web server up and running, you can customize it to serve different content. For example, you can create HTML files and serve them using your web server. Here is an example of how you can modify the server code to serve an HTML file:

require 'socket'

server = TCPServer.new('localhost', 3000)

loop do
  client = server.accept

  client.puts "HTTP/1.1 200 OK"
  client.puts "Content-Type: text/html"
  client.puts
  client.puts File.read('index.html')

  client.close
end

In the code above, we are reading the contents of an index.html file and serving it to the client. Make sure to create an index.html file in the same directory as your server.rb file.

Conclusion

Congratulations! You have successfully built your own web server using Ruby. In this tutorial, we covered the basics of creating a simple web server and customizing it to serve different content. We hope this tutorial has been helpful in understanding how web servers work and how you can create your own using Ruby.

Published: June 21, 2024

© 2024 RailsInsights. All rights reserved.