Created
April 29, 2019 12:19
-
-
Save rikuTanide/431085e830e1756bb65886d7c556a561 to your computer and use it in GitHub Desktop.
二つのasync scriptがあり、二個目のscriptタグが先に届く
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require "socket" | |
require 'thwait' | |
server = TCPServer.open(3000) | |
htmlsoc = server.accept | |
threads = [] | |
# htmlを返すソケット | |
threads << Thread.new do | |
while recv = htmlsoc.readline | |
p recv | |
break if recv == "\r\n" | |
end | |
body = <<EOS | |
<!DOCTYPE html> | |
<title>hello world</title> | |
<h1>hello</h1> | |
<script async src=script1.js></script> | |
<script async src=script2.js></script> | |
EOS | |
header = <<EOS | |
HTTP/1.1 200 OK\r | |
Content-Type: text/html; charset=utf-8\r | |
Content-Length: #{body.bytesize}\r | |
\r | |
EOS | |
p htmlsoc.write(header) | |
p htmlsoc.write(body) | |
htmlsoc.close | |
end | |
# jsリクエスト1 | |
# 先にリクエストが届き、後からレスポンスする | |
async1soc = server.accept | |
threads << Thread.new do | |
while recv = async1soc.readline | |
p recv | |
break if recv == "\r\n" | |
end | |
sleep(1) | |
body = <<EOS | |
const div1 = document.createElement("div"); | |
div1.textContent = "async1.js"; | |
document.body.append(div1); | |
EOS | |
header = <<EOS | |
HTTP/1.1 200 OK\r | |
Content-Type: application/javascript; charset=utf-8\r | |
Content-Length: #{body.bytesize}\r | |
\r | |
EOS | |
p async1soc.write(header) | |
p async1soc.write(body) | |
async1soc.close | |
end | |
# jsリクエスト2 | |
# 後からリクエストが来て、先にレスポンスする | |
async2soc = server.accept | |
threads << Thread.new do | |
while recv = async2soc.readline | |
p recv | |
break if recv == "\r\n" | |
end | |
body = <<EOS | |
const div2 = document.createElement("div"); | |
div2.textContent = "async2.js"; | |
document.body.append(div2); | |
EOS | |
header = <<EOS | |
HTTP/1.1 200 OK\r | |
Content-Type: application/javascript; charset=utf-8\r | |
Content-Length: #{body.bytesize}\r | |
\r | |
EOS | |
p async2soc.write(header) | |
p async2soc.write(body) | |
async2soc.close | |
end | |
thall = ThreadsWait.new(*threads) | |
thall.all_waits{|th| | |
printf("end %s\n", th.inspect) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment