3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RubyでTCP/HTTPサーバを立てる

Last updated at Posted at 2018-05-24

当投稿は主に以下のブログの翻訳です。
Building a 30 line HTTP server in Ruby

ブログにて詳細な説明をしています。
RubyでHTTPサーバを立てる①(ブログ)

[追記]
この記事の続きを書きました。
合わせてご覧ください。
RubyでHTTPサーバを立てる②(ブログ)
RubyでHTTPサーバを立て、その上でRailsを動かす(Qiita)

ソースコードはGitHubにアップしています。

以下、ソースコードのみ貼り付けます。

tcp_server.rb
require 'socket'
server = TCPServer.new(5678)

while session = server.accept
  session.puts "hello time is #{Time.now}"
  session.close
end
tcp_client.rb
require 'socket'
server = TCPSocket.new 'localhost', 5678

while line = server.gets
  puts line
end

server.close
http_server.rb
require 'socket'
require 'rack'
require 'rack/lobster'

app = Rack::Lobster.new
server = TCPServer.new 5678

while session = server.accept
  request = session.gets
  puts request

  method, full_path = request.split(' ')
  path, query = full_path.split('?')

  status, headers, body = app.call({
    'REQUEST_METHOD' => method,
    'PATH_INFO' => path,
    'QUERY_STRING' => query
  })

  session.print "HTTP/1.1 #{status}\r\n"

  headers.each do |key, value|
    session.print "#{key}: #{value}\r\n"
  end

  session.print "\r\n"

  body.each do |part|
    session.print part
  end
  
  session.close
end

http_server.rb を起動してブラウザで見ると、以下のような見た目のはずです。
image.png

3
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?