[rubygems/rubygems] Use a constant empty tar header to avoid extra allocations
[ruby.git] / sample / dualstack-httpd.rb
blobab02e17aea9a224d2ffe6230a39fc3917e0d44a9
1 # simple httpd
3 # The code demonstrates how a multi-protocol daemon should be written.
5 require "socket"
7 port = 8888
8 res = Socket.getaddrinfo(nil, port, nil, Socket::SOCK_STREAM, nil, Socket::AI_PASSIVE)
9 sockpool = []
10 names = []
11 threads = []
13 res.each do |i|
14   s = TCPServer.new(i[3], i[1])
15   n = Socket.getnameinfo(s.getsockname, Socket::NI_NUMERICHOST|Socket::NI_NUMERICSERV).join(" port ")
16   sockpool.push s
17   names.push n
18 end
20 (0 .. sockpool.size - 1).each do |i|
21   mysock = sockpool[i]
22   myname = names[i]
23   STDERR.print "socket #{mysock} started, address #{myname}\n"
24   threads[i] = Thread.start do          # Thread.start cannot be used here!
25     ls = mysock # copy to dynamic variable
26     t = Thread.current
27     STDERR.print "socket #{myname} listener started, pid #{$$} thread #{t}\n"
28     while true
29       as = ls.accept
30       Thread.start do
31         STDERR.print "socket #{myname} accepted, thread ", Thread.current, "\n"
32         s = as  # copy to dynamic variable
33         str = ''
34         while line = s.gets
35           break if line == "\r\n" or line == "\n"
36           str << line
37         end
38         STDERR.print "socket #{myname} got string\n"
39         s.write("HTTP/1.0 200 OK\n")
40         s.write("Content-type: text/plain\n\n")
41         s.write("this is test: my name is #{myname}, you sent:\n")
42         s.write("---start\n")
43         s.write(str)
44         s.write("---end\n")
45         s.close
46         STDERR.print "socket #{myname} processed, thread ", Thread.current, " terminating\n"
47       end
48     end
49   end
50 end
52 for t in threads
53   t.join
54 end