Created
April 29, 2019 12:10
-
-
Save rikuTanide/612126c813f67fc28f6fafb7b534cdfc to your computer and use it in GitHub Desktop.
HTML送信中にスクリプトが届く
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を返すソケット | |
# 途中で送信が1秒つまる | |
threads << Thread.new do | |
while recv = htmlsoc.readline | |
p recv | |
break if recv == "\r\n" | |
end | |
body1 = <<EOS | |
<!DOCTYPE html> | |
<title>hello world</title> | |
<h1>hello</h1> | |
<script async src=script1.js></script> | |
<script defer src=script2.js></script> | |
******* <br> | |
EOS | |
body2 = <<EOS | |
******* | |
EOS | |
length = body1.bytesize + body2.bytesize | |
p length | |
header = <<EOS | |
HTTP/1.1 200 OK\r | |
Content-Type: text/html; charset=utf-8\r | |
Content-Length: #{length}\r | |
\r | |
EOS | |
p htmlsoc.write(header) | |
p htmlsoc.write(body1) | |
sleep(1) | |
p htmlsoc.write(body2) | |
htmlsoc.close | |
end | |
## asyncの方のJS | |
asyncsoc = server.accept | |
threads << Thread.new do | |
while recv = asyncsoc.readline | |
p recv | |
break if recv == "\r\n" | |
end | |
body = <<EOS | |
const div1 = document.createElement("div"); | |
div1.textContent = "asyncの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 asyncsoc.write(header) | |
p asyncsoc.write(body) | |
asyncsoc.close | |
end | |
## deferの方のJS | |
defersoc = server.accept | |
threads << Thread.new do | |
while recv = defersoc.readline | |
p recv | |
break if recv == "\r\n" | |
end | |
body = <<EOS | |
const div2 = document.createElement("div"); | |
div2.textContent = "deferの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 defersoc.write(header) | |
p defersoc.write(body) | |
defersoc.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